JDBC 可做三件事:與數據庫建立連接、發送操作數據庫的語句並處理結果。
而程序首先要做的就是加載數據庫驅動,這裡我使用的是mysql:
1 String driverName=new String("com.mysql.jdbc.Driver");
2 Class.forName(driverName);
然後再獲取數據庫連接對象,參數為數據庫的url,用戶名以及密碼。這裡我使用的數據庫名為jdbc,用戶名為root,密碼為123456:
1 String url=new String("jdbc:mysql://localhost:3306/jdbc");
2 String user=new String("root");
3 String password=new String("123456");
4 Connection coon=DriverManager.getConnection(url, user, password);
因為要對數據庫進行操作,所以要獲取Statement對象:
1 Statement statement = connection.createStatement();
statement對象內封裝的execute(String sql)方法以及executeQuery(String sql)方法和executeUpdate(String sql)方法可以用來執行sql語句,以此來實現對數據庫的操作。
1 String sql = null;
2 ResultSet resultSe = null;
3
4 //創建Student表
5 sql="create table Student (id char(9) primary key,name char(9) unique)";
6 statement.execute(sql);
7
8 //添加元組
9 sql = "insert into Student (id,name) values ('0001','zhangsan')";
10 statement.executeUpdate(sql);
11
12 //查詢Student表
13 sql="select * from Student";
14 resultSet = statement.executeQuery(sql);
15
16 while(resultSet.next()){
17 System.out.println("name:"+resultSet.getString("name"));
18 System.out.println("id:"+resultSet.getString("id"));
19 }
20
21 //刪除元組
22 sql="delete from Student where id='0001'";
23 statement.executeUpdate(sql);
24
25 //刪除表Student
26 sql="drop table Teacher";
27 statement.execute(sql);
操作完數據庫之後要關閉資源,順序依次為resultSet,statement,connection:
1 try {
2 if (resultSet != null)
3 resultSet.close();
4 } catch (SQLException e) {
5 e.printStackTrace();
6 } finally {
7 resultSet = null;
8 try {
9 if (statement != null)
10 statement.close();
11 } catch (SQLException e) {
12 e.printStackTrace();
13 } finally {
14 statement = null;
15 try {
16 if (connection != null)
17 connection.close();
18 } catch (SQLException e) {
19 e.printStackTrace();
20 } finally {
21 connection = null;
22 }
23 }
24 }
close()會拋出異常,需要try/catch語句塊。為保證資源的釋放,需要將close()方法的調用放在finally語句塊裡,釋放資源前判斷對象是否為null。至此,利用jdbc連接數據庫進行簡單的操作算是完成了。