連接數(shù)據(jù)庫
JAVA 如何連接 數(shù)據(jù)庫的
import java.sql.*;
public class JDBCTest {
public static void main(String[] args){
? ? ? ? ? ?// 驅(qū)動程序名 ? ? ? ? ??
String driver = "com.mysql.jdbc.Driver";
? ? ? ? ? ?// URL指向要訪問的數(shù)據(jù)庫名scutcs ? ? ? ??
String url = "jdbc:mysql://127.0.0.1:3306/大家好";
? ? ? ? ? ?// MySQL配置時的用戶名 ? ? ? ? ?
String user = "root"; ? ? ? ? ? ??
// MySQL配置時的密碼 ? ? ? ? ?
String password = "root";
? ? ? ? ? ?try { ? ? ? ? ? ?
? ? ? ? ? // 加載驅(qū)動程序 ? ? ? ??
? ? ? ? ? Class.forName(driver);
? ? ? ? ? ? // 連續(xù)數(shù)據(jù)庫 ? ? ? ? ? ?
? ? ? ? ? Connection conn = DriverManager.getConnection(url, user, password);
? ? ? ? ? ? if(!conn.isClosed()) ? ? ? ? ??
? ? ? ? ? ? System.out.println("連接成功!");
? ? ? ? ? ? // statement用來執(zhí)行SQL語句 ? ? ? ??
? ? ? ? ? ? Statement statement = conn.createStatement();
? ? ? ? ? ? // 要執(zhí)行的SQL語句 ? ? ? ? ?
? ? ? ? ? ? String sql = "select * from 大家好";
? ? ? ? ? ? // 結(jié)果集 ? ? ? ? ??
? ? ? ? ? ? ResultSet rs = statement.executeQuery(sql);
? ? ? ? ? ? while(rs.next()); ?String name="" ; ? ? ? ??
? ? ? ? ? ? // 選擇sname這列數(shù)據(jù) ? ? ? ? ?
? ? ? ? ? ? name = rs.getString("sname");
? ? ? ? ? ? ?// 輸出結(jié)果 ? ? ? ? ?
? ? ? ? ? ? System.out.println(rs.getString("sno") + "\t" + name); ? ? ? ? ? ?
? ? ? ? ? ? rs.close(); ? ? ? ? ? ?conn.close();
? ? ? ? ? ?} catch(ClassNotFoundException e) {
? ? ? ? ? ? System.out.println("沒有驅(qū)動"); ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} catch(SQLException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} catch(Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ?} } }
2016-04-19
....