首先需要到官網下載正確的java數據庫驅動,我用的版本:mysql-connector-java-5.1.47-bin.jar。在Eclipse下建項目sqlDemo,之後導入java數據庫驅動,步驟:點擊項目右鍵,找到“Build Path -> Configure Build Path... -> Libraries -> Add External JARs -> mysql-connector-java-5.1.47-bin.jar ”,最後選擇“OK”確認。
代碼中“testdb”是數據庫名, 需改成自己已創建的數據名,我的數據庫登錄名是“root”,沒有設置登錄密碼,需根據自己登錄名密碼做相應修改。
遇到錯誤提示: WARN: Establishing SSL connection without server's identity verification is not recommended.
請在“jdbc:mysql://localhost:3306/testdb”後面加上“useSSL=false”,正確格式:jdbc:mysql://localhost:3306/testdb?useSSL=false
import java.sql.*;
/**
* @author chen
*
*/
public class SQLTest {
/**
* @param args
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/testdb?useSSL=false";
static final String USER = "root";
static final String PASSWD= "";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("Connnect to database");
conn = DriverManager.getConnection(DB_URL, USER, PASSWD);
stmt = conn.createStatement();
String sql;
sql = "select * from employee";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集數據庫
while(rs.next()){
// 通過字段檢索
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
int age = rs.getInt("age");
float income = rs.getInt("income");
// 輸出數據
System.out.print("\t 姓: " + firstName);
System.out.print("\t 名: " + lastName);
System.out.print("\tage: " + age);
System.out.print("\t income: " + income);
System.out.print("\n");
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt != null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn != null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("GoodBye!");
}
}