1. JDBC的介紹
??jdbc為java開發(fā)者使用數(shù)據(jù)庫提供了統(tǒng)一的編程接口,,它由一組java類和接口組成。 ??訪問數(shù)據(jù)庫的流程
??在連接這一過程中,,一般初學(xué)者是MySQL和java在同一個(gè)電腦上,,建立socket連接,。 ??常用接口:- 一般針對(duì)java開發(fā)使用 Driver接口就行 ,- 在連接數(shù)據(jù)庫時(shí),,需要裝載特定廠商的數(shù)據(jù)驅(qū)動(dòng)程序: ?? MySQL:Class.forname(‘com.mysql.jdbc.Driver’); ?? Oracle:Class.forname(‘oracle.jdbc.driver.OracleDriver’);
2.JDBC重要的API(以MySQL為例)
建立連接:
@Test
public void getConnect(){
try {
//加載驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//獲取連接
String url="jdbc:mysql://localhost:3306/library";
String user="root";
String password="123456";
Connection connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
Statement 注意:這里Statement- 用于執(zhí)行靜態(tài)SQL語句并返回它所生成的結(jié)果對(duì)象,,這里的Statement有三個(gè)類: ? - Statement由createStatement創(chuàng)建,用于發(fā)送簡單的SQL語句。(不帶參) ? - PreparedStatement:繼承自Statement父類,,由preparedStatement創(chuàng)建,,用于發(fā)送含有一個(gè)或多個(gè)輸入?yún)?shù)的SQL語句。PreparedStatement對(duì)象比Statement對(duì)象效率更高,,并且可以防止SQL注入,。 ? - CallableStatement:繼承自PreparedStatement。由方法prePareCall創(chuàng)建,,用于調(diào)用存儲(chǔ),。 常用的Statement的方法有: ? - execute():運(yùn)行語句,返回是否有結(jié)果集 ? - executeQuery():運(yùn)行select語句,,返回ResultSet結(jié)果集 ? - executeUpdate():運(yùn)行insert/update/delete操作,,返回影響的行數(shù) 相關(guān)代碼:
@Test
public void testStatement() throws SQLException {
//創(chuàng)建Statement
Statement statement = connection.createStatement();
String sql="select * from book";
boolean isNull= statement.execute(sql);
//創(chuàng)建PreparedStatement
sql="select * from book";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement1.executeQuery();
//PreparedStatement防止SQL注入,這里的?表示占位符
sql="select * from book where bid = ?";
PreparedStatement preparedStatement2 = connection.prepareStatement(sql);
preparedStatement2.setObject(1,2);
preparedStatement2.executeQuery();
}
ResultSet 描述:ResultSet 主要是由executeQuery()方法執(zhí)行返回 讀取數(shù)據(jù)的流程圖:
例:
@Test
public void testStatement() throws SQLException {
//創(chuàng)建PreparedStatement
String sql = "select * from book";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement1.executeQuery();
while(resultSet.next()){ //表示是否還有下一個(gè)
System.out.println("bid" resultSet.getInt(1));
System.out.println("bname" resultSet.getString(2));
System.out.println("author" resultSet.getString(3));
}
}
jdbc的批處理
-
注意:如果使用大量的批處理時(shí),建議使用statement,,因?yàn)閜reparedstatement的預(yù)編譯空間有限,,當(dāng)數(shù)據(jù)量特別大時(shí),會(huì)發(fā)生異常,。 例:
@Test
public void testStatement() throws SQLException {
//創(chuàng)建Statement
Statement statement = connection.createStatement();
for (int i = 0; i < 50; i ) {
//獲得當(dāng)前的系統(tǒng)時(shí)間
long timestamp = System.currentTimeMillis();
String sql = "insert into t_date(t_time,t_id) values(" timestamp "," i ")";
//為批處理添加執(zhí)行的SQL語句
statement.addBatch(sql);
}
//執(zhí)行批處理
statement.executeBatch();
//提交事務(wù)
connection.commit();
}
jdbc的事務(wù)
@Test
public void testTransaction() {
//取消自動(dòng)提交
try {
connection.setAutoCommit(false);
//插入一條DML語句
PreparedStatement stetm1 = connection.prepareStatement("insert into book values(1001,'朝花夕拾','魯迅')");
stetm1.execute();
//插入另?xiàng)lDML語句
PreparedStatement stetm2 = connection.prepareStatement("insert into book values(1001,'海賊王','尾田一郎')");
stetm2.execute();
//提交
connection.commit();
} catch (SQLException e) {
try {
//失敗后自動(dòng)回滾
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
CLOB操作: 用于存儲(chǔ)大量的文本數(shù)據(jù),,大字段的操作常常以流的方式處理。而非一般的字段一次讀取即可,。
//代碼實(shí)現(xiàn):
public class ReadAndWriteClob {
public static void main(String[] args) {
//獲取數(shù)據(jù)庫連接
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library",
"root",
"123456");
//clob字段插入
//表:user_info
//字段:name varchar , introduce clob
String sql = "insert into user_info values(?,?)";
PreparedStatement prepared1 = conn.prepareStatement(sql);
//插入數(shù)據(jù)
prepared1.setObject(1, "user1");
//設(shè)置插入文本對(duì)象,,第二個(gè)參數(shù)是一個(gè)輸入流,直接讀取文件
prepared1.setClob(2,new BufferedReader(
new InputStreamReader(
new FileInputStream("src/a.txt"))));
prepared1.execute();
//clob字段讀取
sql="select * from user_info";
PreparedStatement prepared2 =conn.prepareStatement(sql);
ResultSet resultSet = prepared2.executeQuery();
while(resultSet.next()){
Clob introduce = resultSet.getClob("introduce");
Reader characterStream = introduce.getCharacterStream();
int temp=0;
while((temp=characterStream.read())!=-1){
System.out.print((char)temp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
BLOB操作: 用于存儲(chǔ)大量的二進(jìn)制數(shù)據(jù),,二進(jìn)制可以存入任何類型的文件(音頻,、視頻等等..)。
//代碼實(shí)現(xiàn)
public class ReadAndWriteClob {
public static void main(String[] args) {
//獲取數(shù)據(jù)庫連接
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library",
"root",
"123456");
//clob字段插入
//表:user_info
//字段:name varchar , headImg blob
String sql = "insert into user_info values(?,?)";
PreparedStatement prepared1 = conn.prepareStatement(sql);
//插入數(shù)據(jù)
prepared1.setObject(1, "user1");
//設(shè)置插入圖片對(duì)象,,第二個(gè)參數(shù)是一個(gè)基本輸入流
prepared1.setBlob(2,new FileInputStream("src/a.jpg"));
prepared1.execute();
//clob字段讀取
sql="select * from user_info";
PreparedStatement prepared2 =conn.prepareStatement(sql);
ResultSet resultSet = prepared2.executeQuery();
while(resultSet.next()){
Blob headImg = resultSet.getBlob("headImg");
//獲取的是基本的流,,
InputStream binaryStream = headImg.getBinaryStream();
int len=0;
byte flush []=new byte [1025];
OutputStream os=new FileOutputStream(new File("d:\\c.jpg"));
while((len=binaryStream.read(flush))!=-1){
os.write(flush,0,len);
os.flush();
}
os.close();
binaryStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
對(duì)jdbc的封裝 這里需要加載配置文件:
代碼實(shí)現(xiàn):
public class jdbcUtils {
private static Properties pro;
static {
try {
pro = new Properties();
InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("dbproperties.properties");
pro.load(in);
Class.forName(pro.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
//建立與數(shù)據(jù)庫的連接
public static Connection getMySQLConn(){
try {
return DriverManager.getConnection(pro.getProperty("url"),
pro.getProperty("user"),
pro.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 關(guān)閉順序:resultSet --?preparStatement --? Connection
* 在關(guān)閉時(shí),不能講這三者的close()寫在同一個(gè)try{}catch{}中
*/
public static void close(Statement stem,ResultSet rs,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stem!=null){
try {
stem.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} 來源:http://www./content-4-103651.html
|