連接數據庫
JAVA 如何連接 數據庫的
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/大家好";
? ? ? ? ? ?// 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("連接成功!");
? ? ? ? ? ? // statement用來執行SQL語句 ? ? ? ??
? ? ? ? ? ? Statement statement = conn.createStatement();
? ? ? ? ? ? // 要執行的SQL語句 ? ? ? ? ?
? ? ? ? ? ? String sql = "select * from 大家好";
? ? ? ? ? ? // 結果集 ? ? ? ? ??
? ? ? ? ? ? ResultSet rs = statement.executeQuery(sql);
? ? ? ? ? ? while(rs.next()); ?String name="" ; ? ? ? ??
? ? ? ? ? ? // 選擇sname這列數據 ? ? ? ? ?
? ? ? ? ? ? name = rs.getString("sname");
? ? ? ? ? ? ?// 輸出結果 ? ? ? ? ?
? ? ? ? ? ? System.out.println(rs.getString("sno") + "\t" + name); ? ? ? ? ? ?
? ? ? ? ? ? rs.close(); ? ? ? ? ? ?conn.close();
? ? ? ? ? ?} catch(ClassNotFoundException e) {
? ? ? ? ? ? System.out.println("沒有驅動"); ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} catch(SQLException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} catch(Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} } }
2016-04-19
....