jdbc基礎 (一) MySQL的簡單使用,jdbc基礎mysql使用
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 //刪除表Student26 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串連資料庫進行簡單的操作算是完成了。