jdbc基礎 (一) MySQL的簡單使用,jdbc基礎mysql使用

來源:互聯網
上載者:User

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串連資料庫進行簡單的操作算是完成了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.