對於jdbc連接數據庫,我這裡的數據庫是mysql,我把它分為四個步驟,這個每個人都有自己的分法,大體基本過程還是相差不大。
第一步:加載數據庫驅動,這裡是加載mysql的驅動,註意,你的自己去下載一個mysql驅動,版本不限。
[java]
try {
Class.forName("com.mysql.jdbc.Driver");//加載MySql的驅動類
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("找不到MYSQL驅動類");
e.printStackTrace();
}
第二步:創建連接,先申明一個Connection 變量,把數據庫url也準備好,我這的URL是:
[java]
private String url="jdbc:mysql://localhost:3306/stu?user=root&password=123456";//密碼設置自己的數據庫密碼
然後執行以下:
[java]
try {
con=DriverManager.getConnection(url);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("連接失敗!");
e.printStackTrace();
}
第三步:那就是做你要查詢或者修改,刪除之類的事情瞭,我這裡隻做瞭個查詢的小例子:
[java]
public void chaxun()
{
String query = "select * from 09xinji where id=2";
String bu;
Statement stmt=null;
ResultSet rs=null;
try {
stmt = con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
bu="學號:"+rs.getObject(1)+' '+"姓名:"+rs.getObject(2)+' '+"性別:"+rs.getObject(3)+" 年齡:"+rs.getObject(4);
System.out.println(bu);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
這裡隻是查詢瞭一個記錄,對於多個記錄查詢的結果我還沒研究過怎麼儲存起來,我有時間補一下。
第四部:既然我們打開瞭連接,不用的時候就要記得關閉,不然會占用系統的資源的,特別是服務器端的程序,大量的連接會導致崩潰的結果,所以用完瞭就關瞭它!
[html] view plaincopyprint?
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
做完四部,基本可以做些簡單的數據處理瞭。
我把它完整的整理一下,並把顯示效果圖也貼一下:
[html]
import java.sql.*;
public class Shujukucon {
private Connection con=null;
private String url="jdbc:mysql://localhost:3306/stu?user=root&password=123456";//密碼設置自己的數據庫密碼
public Connection getcon()
{
try {
Class.forName("com.mysql.jdbc.Driver");//加載MySql的驅動類
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("找不到MYSQL驅動類");
e.printStackTrace();
}
try {
con=DriverManager.getConnection(url);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("連接失敗!");
e.printStackTrace();
}
System.out.println("連接成功!");
return con;
}
//連接成功瞭,就來試一下查詢數據
public void chaxun()
{
String query = "select * from 09xinji where id=2";
String bu;
Statement stmt=null;
ResultSet rs=null;
try {
stmt = con.createStatement();
rs=stmt.executeQuery(query);
while(rs.next())
{
bu="學號:"+rs.getObject(1)+' '+"姓名:"+rs.getObject(2)+' '+"性別:"+rs.getObject(3)+" 年齡:"+rs.getObject(4);
System.out.println(bu);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Shujukucon sjk=new Shujukucon();
sjk.getcon();
sjk.chaxun();
}
}
作者:yinqianhui1990