import java.sql.*;
public class JDBCTest {
public static void main(String[] args){
// 驅動程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要訪問的數據庫名scutcs
String url = "jdbc:mysql://127.0.0.1:3306/scutcs";
// MySQL配置時的用戶名
String user = "root";
// MySQL配置時的密碼
String password = "root";
try {
// 加載驅動程序
Class.forName(driver);
// 連續數據庫
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用來執行SQL語句
Statement statement = conn.createStatement();
// 要執行的SQL語句
String sql = "select * from student";
// 結果集
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("執行結果如下所示:");
System.out.println("-----------------");
System.out.println(" 學號" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
while(rs.next()) {
// 選擇sname這列數據
name = rs.getString("sname");
// 首先使用ISO-8859-1字符集將name解碼爲字節序列並將結果存儲新的字節數組中。
// 然後使用GB2312字符集解碼指定的字節數組
name = new String(name.getBytes("ISO-8859-1"),"GB2312");
// 輸出結果
System.out.println(rs.getString("sno") + "\t" + name);
}
rs.close();
conn.close();
} catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
java database
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.