jdbc文件的形式進行書寫程式碼
阿新 • • 發佈:2018-12-13
package com.java.test1; import java.security.interfaces.RSAKey; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;
public class JdbcTest2 {
public static void main(String[] args) { Connection connection = null; Statement st = null; ResultSet resultSet = null; //Driver driver = //1.註冊驅動 try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //建立連線 引數一 引數二 引數三 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student1", "root", "root"); connection.createStatement(); // 3建立statement,和資料庫打交道一定需要這個對像 st = connection.createStatement(); //4查詢 String sql = "select *from list"; resultSet = st.executeQuery(sql); while(resultSet.next()){ int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String age = resultSet.getString("age"); //輸出的上面變數接收的返回值 System.out.println("id="+id+"name="+name+"age="+age); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //第五步驟是嚴格按照jdbc的api格式進行書寫程式碼的 }finally { //5.釋放order 按照順序進行釋放 if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } resultSet = null; } if(st != null ){ try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } st = null; } if(connection != null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connection = null; } } }
}