我用的數據庫名是:test
賬號密碼都是:root
=================================
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
// 1. 註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
// 聲明變量,使用,而後關閉
Connection conn = null; //數據庫連接
Statement stmt = null; //數據庫表達式
ResultSet rs = null; //結果集
try {
//2. 獲取數據庫的連接
conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/test","root","root");
//3. 獲取表達式
stmt = conn.createStatement();
//4. 執行SQL
String sql = "select time from shijian where id=123";
rs = stmt.executeQuery(sql);
//5. 現實結果集裏面的數據
while(rs.next()) {
System.out.println("id為123的time值=" + rs.getString(1));
}
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
if(rs != null) {
rs.close();
}
if(stmt!= null) {
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}