import java.sql.*;
public class TestJDBC {
public static void main(String[] arges) throws SQLException,ClassNotFoundException{
String user="root";
String pwd="mysql";
//設定URL
String myjdbc="jdbc:mysql://localhost:3306/test";
//加載MYSQL驅動
Class.forName("com.mysql.jdbc.Driver");
//創建連接會話
Connection myConnection=DriverManager.getConnection(myjdbc,user,pwd);
//創建語句塊對象
Statement Myoperation=myConnection.createStatement();
//獲取結果集對象
ResultSet record=Myoperation.executeQuery("select *from test");
while(record.next()){
//輸出結果集對象
System.out.println(record.getInt("id")+","+record.getString("name"));
}
//關閉結果集
try{
if(record!=null)
//關閉結果集時需要處理異常
record.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(myConnection!=null)
myConnection.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
本文出自 “java技術社區” 博客