天天看點

一個JDBC小例子

package com.imau.entity;

import java.sql.*;

public class testPrep {

public static void main(String[] args) {

// 聲明Connection對象

Connection con;

// 資料庫驅動

String DRIVER = "com.mysql.jdbc.Driver";

// 3306後面為資料庫名字 

String url = "jdbc:mysql://localhost:3306/testdb";

String username = "root";

// 資料庫密碼

String password = "123456";

try {

// 注冊驅動

Class.forName(DRIVER);

// 1.getConnection()方法,連接配接MySQL資料庫!!

con = DriverManager.getConnection(url, username, password);

if (!con.isClosed())

System.out.println("Succeeded connecting to the Database!");

// 2.建立statement類對象,用來執行SQL語句!!

String sql = "select * from student";

//String insertsql ="insert into student values(2014123,'紅塵','女',89,97);";

//String deletesql ="delete from student where id=2014123";

String updatesql = "update student set sex='女' where name='張三'";

PreparedStatement statement = con.prepareStatement(updatesql);

PreparedStatement statement2 = con.prepareStatement(sql);

// 3.ResultSet類,用來存放擷取的結果集!!

int re = statement.executeUpdate();

System.out.println("插入了"+re+"行");

ResultSet rs = statement2.executeQuery();

System.out.println("----------------------------------");

System.out.println("執行結果如下所示:");

System.out.println("----------------------------------");

System.out.println(" id" + "\t" + " 姓名" + "\t" + "性别" + "\t" + "數學" + "\t" + "英語");

System.out.println("----------------------------------");

String sid = null;

String sname = null;

String ssex = null;

String smath = null;

String sEnglish = null;

while (rs.next()) {

sid = rs.getString("id");// 從表的第一列取資料

sname = rs.getString("name");

ssex = rs.getString("sex");

smath = rs.getString("math");

sEnglish = rs.getString("English");

System.out.println(sid + "\t" + sname + "\t" + ssex + "\t" + smath + "\t" + sEnglish);

}

rs.close();

con.close();

} catch (ClassNotFoundException e) {

// 資料庫驅動類異常處理

System.out.println("Sorry,can`t find the Driver!");

e.printStackTrace();

} catch (SQLException e) {

// 資料庫連接配接失敗異常處理

e.printStackTrace();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally {

// System.out.println("資料庫資料成功擷取!!");

}

}

}