1、java.sql.Drivermanager類:創(chuàng)建連接
a、注冊驅(qū)動
DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建議使用
原因有2個:
>導致驅(qū)動被注冊2次。
>強烈依賴數(shù)據(jù)庫的驅(qū)動jar
解決辦法:
Class.forName("com.mysql.jdbc.Driver");
b、與數(shù)據(jù)庫建立連接
static Connection getConnection(String url, Stringuser, String password)
試圖建立到給定數(shù)據(jù)庫URL的連接。
getConnection("jdbc:mysql://localhost:3306/day06",
"root", "root");
URL:SUN公司與數(shù)據(jù)庫廠商之間的一種協(xié)議。
jdbc:mysql://localhost:3306/day06
協(xié)議子協(xié)議IP :端口號數(shù)據(jù)庫
mysql: jdbc:mysql://localhost:3306/day14或者jdbc:mysql:///day14(默認本機連接)
oracle: jdbc:oracle:thin:@localhost:1521:sid
Propertiesinfo = new Properties();//要參考數(shù)據(jù)庫文檔
info.setProperty("user","root");
info.setProperty("password","root");
getConnection(String url, Properties info)
getConnection(String url)
DriverManager.getConnection("jdbc:mysql://localhost:3306/day14?user=root&password=root");
2、java.sql.Connection接口:一個連接
接口的實現(xiàn)在數(shù)據(jù)庫驅(qū)動中。所有與數(shù)據(jù)庫交互都是基于連接對象的。
StatementcreateStatement(); //創(chuàng)建操作sql語句的對象
3、java.sql.Statement接口:操作sql語句,并返回相應結果的對象
接口的實現(xiàn)在數(shù)據(jù)庫驅(qū)動中。用于執(zhí)行靜態(tài)SQL語句并返回它所生成結果的對象。
ResultSetexecuteQuery(String sql)根據(jù)查詢語句返回結果集。只能執(zhí)行select語句。
int executeUpdate(String sql)根據(jù)執(zhí)行的DML(insert
update delete)語句,返回受影響的行數(shù)。
booleanexecute(String sql)此方法可以執(zhí)行任意sql語句。返回boolean值,表示是否返回ResultSet結果集。僅當執(zhí)行select語句,且有返回結果時返回true,其它語句都返回false;
4、java.sql.ResultSet接口:結果集
a、封裝結果集的。
提供一個游標,默認游標指向結果集第一行之前。
調(diào)用一次next(),游標向下移動一行。
提供一些get方法。
封裝數(shù)據(jù)的方法
Object
getObject(int columnIndex);根據(jù)序號取值,索引從1開始
Object
getObject(String ColomnName);根據(jù)列名取值。
將結果集中的數(shù)據(jù)封裝到javaBean中
java的數(shù)據(jù)類型與數(shù)據(jù)庫中的類型的關系
byte ?tityint
short ?smallint
int ? int
long ?bigint
float ?float
double ?double
Stringchar varchar
Date ?date
boolean next()將光標從當前位置向下移動一行
int getInt(int colIndex)以int形式獲取ResultSet結果集當前行指定列號值
int getInt(String colLabel)以int形式獲取ResultSet結果集當前行指定列名值
float getFloat(int colIndex)以float形式獲取ResultSet結果集當前行指定列號值
float getFloat(String colLabel)以float形式獲取ResultSet結果集當前行指定列名值
String getString(int colIndex)以String形式獲取ResultSet結果集當前行指定列號值
String getString(String colLabel)以String形式獲取ResultSet結果集當前行指定列名值
Date getDate(int columnIndex);
Date getDate(String columnName);
void close()關閉ResultSet對象
b、可移動游標的方法
boolean next()將光標從當前位置向前移一行。
boolean previous()
將光標移動到此ResultSet對象的上一行。
boolean absolute(int row)參數(shù)是當前行的索引,從1開始
根據(jù)行的索引定位移動的指定索引行。
void afterLast()
將光標移動到末尾,正好位于最后一行之后。
void beforeFirst()
將光標移動到開頭,正好位于第一行之前。
5、釋放資源
資源有限,要正確關閉。