JDBC是Java Database Connectivity(Java數(shù)據(jù)庫連接)的縮寫,它有一組用Java語言編寫的類和接口組成。通過JDBC,開發(fā)人員可以使用Java語言編寫各種復(fù)雜的數(shù)據(jù)庫應(yīng)用程序。JDBC已經(jīng)成為Java語言訪問數(shù)據(jù)庫使用的標(biāo)準(zhǔn)API。如合通過JDBC訪問數(shù)據(jù)庫呢?主要有以下幾步:
1、加載數(shù)據(jù)庫驅(qū)動(dòng)。(JDBC本身并不能直接訪問數(shù)據(jù)庫,它需要依賴于JDBC驅(qū)動(dòng)程序。)
2、與數(shù)據(jù)庫建立連接。(格式:DriverManager.getConnection("jdbc:mysql://localhost<或?qū)?27.0.0.1>:端口號/數(shù)據(jù)庫名","用戶名", "進(jìn)入數(shù)據(jù)庫的密碼");)
3、發(fā)送查詢或更新語句到數(shù)據(jù)庫。
4、執(zhí)行查詢并返回查詢結(jié)果。
看一下下面的小例子。
/**
* DriverManager 驅(qū)動(dòng)程序管理器 在數(shù)據(jù)庫和相應(yīng)驅(qū)動(dòng)程序之間建立連接
* Connection 對象代表與數(shù)據(jù)庫的連接,也就是在已經(jīng)加載的Driver和數(shù)據(jù)庫之間建立連接
* Statement 提供在基層連接上運(yùn)行SQL語句,并且訪問結(jié)果
* ResultSet 在Statement執(zhí)行SQL語句時(shí),有時(shí)會返回ResultSet結(jié)果集,包含的是查詢的結(jié)果集
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Tester {
public static void main(String[] args) {
query();
}
public static void query(){
Connection conn = null;
try {
//1.加載數(shù)據(jù)庫驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//DriverManager 驅(qū)動(dòng)程序管理器 在數(shù)據(jù)庫和相應(yīng)驅(qū)動(dòng)程序之間建立連接
//2.獲得數(shù)據(jù)庫連接
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc_db", "root", "1234");
//3.創(chuàng)建語句
String sql = "select * from UserTbl";
//返回一個(gè)執(zhí)行SQL的句柄
Statement stmt = conn.createStatement();
//返回查詢的
//4.執(zhí)行語句
ResultSet rs = stmt.executeQuery(sql);
//5.遍歷結(jié)果集
while(rs.next()){
int id = rs.getInt(1);
String username = rs.getString(2);
String password = rs.getString(3);
int age = rs.getInt(4);
System.out.println(id+":"+username+":"+password+":"+age);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn!=null){
try { //關(guān)閉數(shù)據(jù)庫連接
conn.close();
} catch (SQLException e) {
conn = null;
e.printStackTrace();
}
}
}
}
}
運(yùn)行結(jié)果:
要注意的是在獲得數(shù)據(jù)庫連接時(shí)根據(jù)你所用的數(shù)據(jù)庫種類選擇加載的connector。加載方法先將連接數(shù)據(jù)庫的jar包放進(jìn)你的Project的一個(gè)Folder內(nèi),然后右擊選擇build path-----add to build path就可以了。第三步創(chuàng)建的SQL應(yīng)根據(jù)你具體的需要編寫。
獲得數(shù)據(jù)庫連接還可以通過下面兩種方法:
// 第一種方法
public Connection getConnection(String driver, String url, String user,
String password) {
Connection conn = null;
try {
// Class.forName加載驅(qū)動(dòng)
Class.forName(driver);
// DriverManager獲得連接
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 第二種方法
public Connection openConnection() {
String driver = "";
String url = "";
String user = "";
String password = "";
Properties prop = new Properties();
Connection conn = null;
try {
// 加載屬性文件
prop.load(this.getClass().getClassLoader().getResourceAsStream(
"DBConfig.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
// Class.forName加載驅(qū)動(dòng)
Class.forName(driver);
// DriverManager獲得連接
conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
第二種方法比較常用,因?yàn)樽鲂薷牡臅r(shí)候不需要對程序進(jìn)行大的修改,只要在配置文件中進(jìn)行增、刪、改就可以了。
寫一下關(guān)于數(shù)據(jù)庫表的操作SQL,內(nèi)容不重要,重要的是理解結(jié)構(gòu)和含義哈。
//有自增的語句
CREATE TABLE person(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT ,
name VARCHAR(20) NOT NULL ,
age INT
) ;
/*創(chuàng)建學(xué)生表*/
create table Student(
Sno char(9) primary key,/*列級玩整性約束條件,Sno是主碼*/
Sname char(20) unique, /*Sname 取唯一值*/
Ssex char(2),
Sage smallint,
Sdept char (20),
);
/*創(chuàng)建課程表*/
create table Course(
Cno char(4) primary key, /*列表完整性約束條件,Cno是主碼*/
Cname char(40),
Cpno char(4), /*Cpno的含義是先修課*/
Ccredit smallint,
foreign key (Cpno) references Course(Cno)
/*表級完整性的約束條件,Cpno是外碼,被參照表是Course,被參照列式Cno*/
);
/*創(chuàng)建學(xué)生課程表*/
create table SC(
Sno char (9),
Cno char(4),
Grade smallint,
primary key(Sno,Cno),/*主碼由兩個(gè)屬性構(gòu)成,必須作為表級完整性進(jìn)行定義*/
foreign key (Sno) references Student(Sno),/*表級完整性約束條件,Sno是外碼,被參照表是Student*/
foreign key (Cno) references course(Cno),/*表級完整性約束條件,Sno是外碼,被參照表是Student*/
);
/*向Student表增加“入學(xué)時(shí)間”列 */
alter table Student add S_entrance date;
/*修改Student中Sage的屬性*/
alter table Student alter column Sage int;
/*修改Course表中Cname為唯一值*/
alter table Course add unique (Cname);
/*刪除表Student*/
Drop Table Student Cascade;(cascade 刪除表是該表沒有限制條件,在刪除基本表的同時(shí),相關(guān)的依賴對象,例如 視圖等,都被刪除
restrict刪除的表不能被其他約束所引用,不能有視圖,觸發(fā)器。存儲過程或函數(shù)等 )
/*** 表的索引 ***/
/*在Student表的Sname列上建立一個(gè)聚族索引*/
create cluster intdex Stusname on Student(Sname);
/*在三個(gè)表中建立唯一索引*/
create unique index Stuno on Student(Sno);
create unique index Coucno on Course(Cno);
create unique index SCno on SC(Sno ASC, Cno DESC);
/*刪除Student表中stusname索引*/
drop index Student;
/*** 數(shù)據(jù)查詢 ***/
一、普通查詢
//查詢?nèi)w學(xué)生的詳細(xì)記錄
select *
from Student;
//查詢經(jīng)過計(jì)算的值
select Sname ,2004-Sage
from Student;
//查詢?nèi)w學(xué)生的姓名、出生年份和所在的院系,要求用小寫的字母表示所有系名
1、select Sname,'year of birth:' birth, 2004-Sage birthday,LOWER(Sdept) departement
from Student;
2、select Sname,'year of birth:', 2004-Sage ,LOWER(Sdept)
from Student;
//查詢選修課程的學(xué)生學(xué)號
select (all)Sno
from SC;
//查詢選修課程的學(xué)生學(xué)號(消除取值重復(fù)的行)
select distinct Sno
from SC;
二、條件查詢
//查詢?nèi)w計(jì)算機(jī)系的所有學(xué)生
select Sname
from Student
where Sdept='CS';
//查詢所有年齡在20歲以下的學(xué)生姓名和年齡
select Sname Sage
from Student
where Sage<20;
//成績有不及格學(xué)生的學(xué)號
select distinct Sno
from SC
where Grade<60;
//年里不在20到30歲之間的學(xué)生姓名、系別、和年齡
select Sname,Sdept,Sage
from Student
where Sage not between 20 and 23;
//查詢在CS、MA、IS學(xué)生的姓名和性別
select Sname,Ssex
from Student
where Sdept in('CS','MA','IS');
//查詢不在CS、MA、IS學(xué)生的姓名和性別
select Sname,Ssex
from Student
where Sdept not in('CS','MA','IS');
//查詢學(xué)號200215121的學(xué)生詳細(xì)情況
select *
from Student
where Sno like '200215121'; (like 可用=替換)
//查詢所有姓劉的學(xué)生姓名和性別
select *
from Student
where Sname like '劉%'; (% 等符號的含義)
//刪除年齡大于25歲的
delete from Student where age>25;