作者:Alvin
功能:數據庫連接與實現增刪改查
時間:2019年3月4日08點33分
參考文章:https://www.2cto.com/database/201805/743741.html
一、總結
數據庫加載分為以下幾個步驟
第一步、加載驅動
MySQL的加載方式 Class.forName("com.mysql.jdbc.Driver"); Oracle的加載方式 Class.forName("oracle.jdbc.driver.OracleDriver"); SQLServer Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
第二步、創建連接
1、分開寫形式如下
String url = "jdbc:mysql://127.0.0.1:3306/要連接的數據庫表名"; String username = "root"; String password = "root"; Connection con = DriverManager.getConnection(url,username,password);
2、單獨寫成形式如下
Connection con=DriverManage.getConnection(url,username,password);
如
Connection con=DriverManage.getConnection("jdbc:mysql://127.0.0.1:3306/要連接的數據庫表名",username,password);
3、設置連接時編碼方式useUnicode=true&characterEncoding=UTF-8,如
String URL ="jdbc:mysql://127.0.0.1:3306/studentsuser=root&password=123&useUnicode=true&characterEncoding=UTF-8"; con = DriverManager.getConnection(URL);
4、確認是否連接成功
//如果連接成功打印con不為空 System.out.println(con);
第三步、創建語句執行對象
Statement stmt=con.createStatement();
第四步、得到數據庫執行操作結果
一般情況下有如下幾個執行類型
1、增加數據
int modifyLinesAdd = stmt.executeUpdate(sql1);//將返回被增加的行數
2、刪除數據
int modifyLinesDelete=stmt.executUpdate("delete from 表名 where 條件");//將返回發生修改的條數
3、修改數據
int modifyLinesSwitch=stmt.executeUpdate();//將返回發生修改的行數
4、查詢操作
ResultSet rs=stmt.executQuery("select from 表名");//執行查詢,返回的時Set集合
所以再只有再進行數據庫查詢的時候使用executeQuery()方法,再增、刪、改的時候執行的都是executeUpdate()方法
還可以向數據庫中添加文件下面以圖片為例(因為時添加操作所以仍然使用的時executeUpdate()方法)
添加圖片數據源碼
File image = new File("C:/Users/lyp/Pictures/桌面背景/1.jpg"); //添加圖片的路徑 ps = con.prepareStatement("INSERT INTO `students`.`students_1` (`id`,`name`, `sex`, `age`,`icon`)" + " VALUES (,,,,);"); ps.setInt(1, numbefore+1); ps.setString(2, "蘭陵王"); ps.setString(3,"男"); ps.setInt(4,500); fis = new FileInputStream(image); ps.setBinaryStream(5, (InputStream) fis, (int) (image.length())); //檢查是否添加成功 int s = ps.executeUpdate(); if (s > 0) { System.out.println("Uploaded successfully !"); } else { System.out.println("unsucessfull to upload image."); }
查詢操作案例
ResultSet rs.stmt.executeQuery("select from student"); //處理執行后的結果rs rs.next()用於判斷下一項是否存在,如果存在,將返回true while(rs.next()){ int id=rs.getInt("id");//得到id這一列的數據 String name=rs.getString("names");//得到姓名 String gender=rs.getString("gender");//得到性別 int age=rs.getAge("age");//得到年齡 }
第五步、執行完畢數據庫的操作必須依次關閉打開的所有連接
//關閉rs rs.close(); //關閉stmt stmt.close(); //關閉con con.close();
二、完整案例源碼
//數據庫類源碼如下 public class DataBase { public static void main(String[] args) { int numbefore = 0; Connection con = null;//鏈接接口 Statement stmt = null;//發送SQL語句接口 ResultSet rs = null;//返回結果集接口 PreparedStatement ps = null; FileInputStream fis; try { //加載驅動 Class.forName("com.mysql.jdbc.Driver"); //連接方法一 /*String url = "jdbc:mysql://127.0.0.1:3306/students";//127.0.0.1可以改成localhost,表示本地主機。 String username = "root"; String password = "root"; con = DriverManager.getConnection(url,username,password);*/ //連接方法二,useUnicode=true&characterEncoding=UTF-8是設置編碼方式 String URL ="jdbc:mysql://127.0.0.1:3306/studentsuser=root&password=123&useUnicode=true&characterEncoding=UTF-8"; con = DriverManager.getConnection(URL); //如果連接成功打印con不為空 System.out.println(con); stmt = con.createStatement(); //con.close(); //查詢數據庫中表的值,並且打印出來 rs = stmt.executeQuery("select * from students_1"); while(rs.next()) { //next()方法控制行數,一行一行讀出返回結果集,直到null int id = rs.getInt("id");//獲取id這一列的數據 String name = rs.getString(2);//獲取第二列數據 String sex = rs.getString("sex"); int age = rs.getInt("age"); System.out.println("編號="+id+",姓名="+name+",性別="+sex+",年齡="+age); //計算表中數據的行數 numbefore = numbefore + 1; } //打印出操作數據前的行數 System.out.println("操作前數據為"+numbefore+"行"); //添加圖片數據 File image = new File("C:/Users/lyp/Pictures/桌面背景/1.jpg"); //添加圖片的路徑 ps = con.prepareStatement("INSERT INTO `students`.`students_1` (`id`,`name`, `sex`, `age`,`icon`)" + " VALUES (,,,,);"); ps.setInt(1, numbefore+1); ps.setString(2, "蘭陵王"); ps.setString(3,"男"); ps.setInt(4,500); fis = new FileInputStream(image); ps.setBinaryStream(5, (InputStream) fis, (int) (image.length())); //檢查是否添加成功 int s = ps.executeUpdate(); if (s > 0) { System.out.println("Uploaded successfully !"); } else { System.out.println("unsucessfull to upload image."); } //添加一行數據 //使用SQL語句:INSERT INTO `students`.`students_1` (`id`, `name`, `sex`, `age`) VALUES ('1','小七', '女', '10'); 添加數據 /*String sql1 = "INSERT INTO `students`.`students_1` (`id`,`name`, `sex`, `age`) VALUES ('1','小七', '女', '10');"; int result1 = stmt.executeUpdate(sql1); System.out.println("有"+result1+"行記錄被修改");*/ //動態添加一行數據 /*ps = con.prepareStatement("INSERT INTO `students`.`students_1` (`id`,`name`, `sex`, `age`) VALUES (,'小七', '女', '10');"); ps.setInt(1, numbefore+1); int result_x = ps.executeUpdate(); System.out.println("有"+result_x+"行記錄被修改");*/ //修改一個數據 //使用SQL語句:UPDATE `students`.`students_1` SET `name` = '康納' WHERE `age` = 12 AND `sex` = '男':修改age=12和sex=男的數據的name為康納 String sql2 = "UPDATE `students`.`students_1` SET `name` = '康納' WHERE `id`= '4' AND `age` = '12' AND `sex` = '男'; "; int result2 = stmt.executeUpdate(sql2); System.out.println("有"+result2+"行記錄被修改"); //刪除一行數據 //使用SQL語句:DELETE FROM `students`.`students_1` WHERE `id` = '5' ; 刪除id=5的一行 /*String sql3 = "DELETE FROM `students`.`students_1` WHERE `id` = '8' ; "; int result3 = stmt.executeUpdate(sql3); System.out.println("有"+result3+"行記錄被修改");*/ } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally {//依次關閉數據庫接口 if(rs!=null) { try { rs.close(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } if(stmt!=null) { try { stmt.close(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } if(con!=null) { try { con.close(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } } } }