JDBC五大步
1加載驅動
2創建鏈接
3編寫SQL語句
4執行SQL語句並獲得結果集
5處理結果集並釋放資源
簡單的總結了一下
我這個數據庫的驅動是鏈接SQLServer 數據庫的
driverClassName com.mysql.jdbc.Driver
url jdbc:mysql://localhost:3306/merch
username root
password root
這是鏈接MYSQL數據庫的
//數據庫驅動
private static final String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//數據庫url
private static final String url="jdbc:sqlserver://localhost:1433;databaseName=******";
//數據庫賬戶和密碼
private static final String user="******",pwd="******";
public static void main(String[] args) {
}
//System.out.println(getConnection());
/**
* 加載驅動,獲取連接
*/
public static Connection getConnection(){
try {
Class.forName(driverName);
return DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 執行數據的增,刪,改 操作
*/
public static int executeUpdate(String sql){
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
try {
conn = getConnection();
stat = conn.createStatement();
return stat.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.getErrorCode()*(-1);
}
}
/**
* 根據相關的sql語句獲取相應的查詢結果
*/
public static ResultSet executeQuery(String sql){
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
try {
conn = getConnection();
stat = conn.createStatement();
return stat.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 關閉連接,釋放資源
*/
public static void closeAll(Connection conn,Statement stat,ResultSet rs){
try {
if(rs !=null)
rs.close();
if(stat!=null)
stat.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}