安裝好mysql數據庫 安裝後檢查是否有connection J 的程序 第一步導入架包,加載驅動程序 發起請求java
第一步的程序 url 若是寫成 jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8 ; 有可能會報錯 ——>java.sql.SQLException: The server time zone value ........ 這時候參考博文:https://blog.csdn.net/Hello_World_QWP/article/details/80421533 也就是用下面個人url 裏 +?......的部分mysql
Class.forName("com.mysql.jdbc.Driver");//通常都是已經加載好的 加入後可能會警告 System.out.println("驅動加載成功"); String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; String user = "root"; String password = "88888888"; Connection con = DriverManager.getConnection(url, user, password);
第二步進行語句操做 查詢完關閉sql
//第二步 進行語句操做 Scanner sc = new Scanner(System.in); //能夠輸入sql查詢語句 Statement stm = con.createStatement(); System.out.println("輸入sql語句"); String sql = sc.nextLine(); ResultSet res = stm.executeQuery(sql); while(res.next()) {//輸出結果集 System.out.println(res.getInt(1)+","+res.getString(2)+","+res.getString(3)); } if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con !=null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); }
完整代碼數據庫
import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.sql.Connection; public class JDBC { public static void main(String[] args) { // 第一步 導入架包 加載驅動程序 // Class.forName("com.mysql.jdbc.Driver");//通常都是已經加載好的 System.out.println("驅動加載成功"); String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; String user = "root"; String password = "88888888"; Connection con = null; Statement stm = null; ResultSet res = null; try { con = DriverManager.getConnection(url, user, password); Scanner sc = new Scanner(System.in); stm = con.createStatement(); System.out.println("輸入sql語句"); String sql = sc.nextLine(); res = stm.executeQuery(sql); while (res.next()) { System.out.println(res.getInt(1) + "," + res.getString(2) + "," + res.getString(3)); } } catch (SQLException e) { e.printStackTrace(); } finally {// 每一個關閉語句都要單獨 放 否則一個有異常 會致使其餘資源的關閉 if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con !=null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } // 第二步 進行語句操做 } }
查詢語句能夠改成apache
System.out.println(res.getInt("id") + "," + res.getString("name") + "," + res.getString("sex"));
整理代碼 把操做寫到方法裏面 查詢數據庫全部信息ide
public static void selectAll() { Connection con = null; Statement stm = null; ResultSet res = null; try { con = DriverManager.getConnection(url, user, password); Scanner sc = new Scanner(System.in); stm = con.createStatement(); res = stm.executeQuery("select * from t1_user"); while (res.next()) { System.out.println(res.getInt("id") + "," + res.getString("name") + "," + res.getString("sex")); } } catch (SQLException e) { e.printStackTrace(); } // 每一個關閉語句都要單獨 放 否則一個有異常 會致使其餘資源的關閉 finally { if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con !=null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
經過 指定的id 和name 來查詢 注意 namevalue 要用單引號括起來工具
public static boolean selectByIdName(String id, String name) {// 查詢語句是否存在指定的id 以及 name Connection con = null; Statement sta = null; ResultSet res = null; try { con = DriverManager.getConnection(url, user, password); sta = con.createStatement(); res = sta.executeQuery("select * from t1_user where id= " + id + " and name = '" + name + "'"); // 有數據就返回true 並輸出相對應的信息 if (res.next()) { while (res.next()) { System.out.println(res.getInt("id") + "," + res.getString("name")); } return true; } else return false; } catch (Exception e) { e.printStackTrace(); } finally { if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con !=null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } }
數據庫要當心sql注入 被黑客攻擊的漏洞 id 和 name 是數據庫裏面沒有的 結果還輸出數據url
防止sql注入 採用 preparedstatement 語句 將上面sql定義的數據改寫爲spa
Connection con = null; PreparedStatement psta = null; ResultSet res = null; try { con = DriverManager.getConnection(url, user, password); String sql = "select * from t1_user where id = ? and name = ?"; psta = con.prepareStatement(sql);//建立後再設置參數 psta.setInt(1, id); psta.setString(2, name); res = psta.executeQuery();//記得要賦值給 res
分頁查詢
limit 查詢的方法 查詢第幾頁.net
public static void selectUserByPage(int pageNumber , int pageCount) { Connection con = null; PreparedStatement pstm =null; ResultSet res = null; try { con = DriverManager.getConnection(url,user,password); String sql = "select * from t1_user limit ? , ?"; pstm = con.prepareStatement(sql); pstm.setInt(1, (pageNumber-1)*pageCount); pstm.setInt(2, pageCount); res = pstm.executeQuery(); while(res.next()) { System.out.println(res.getInt(1)+","+res.getString(2)+","); } } catch (Exception e) { System.out.println(e); }finally { if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con !=null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
對代碼進行整合(重複代碼放到一個工具類中) 以及實現一些小功能
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class JDBCUtills { private static final String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; public static Connection getConn() { Scanner sc = new Scanner(System.in); System.out.println("輸入登錄帳號"); String user = sc.nextLine(); System.out.println("輸入密碼"); String password = sc.nextLine(); Connection con = null; PreparedStatement pstm =null; ResultSet res = null; try { con = DriverManager.getConnection(url,user,password); System.out.println("登錄成功"); return con; } catch (Exception e) { System.out.println("密碼帳號出錯"); } return con; } public static void close(ResultSet res, PreparedStatement pstm, Connection con) { if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(pstm !=null) try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con != null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet res, Statement stm, Connection con) { if(res!=null) try { res.close(); } catch (SQLException e) { e.printStackTrace(); } if(stm !=null) try { stm.close(); } catch (SQLException e) { e.printStackTrace(); } if(con != null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } }
import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.sql.Connection; public class JDBC { static String user; static String password; static String url; static Connection con; public static void main(String[] args) { Scanner sc = new Scanner(System.in); con = JDBCUtills.getConn(); if (con != null) selectAll(); } public static void selectAll() { Statement stm = null; ResultSet res = null; try { stm = con.createStatement(); res = stm.executeQuery("select * from t1_user"); while (res.next()) System.out.println(res.getInt("id") + "," + res.getString("name") + "," + res.getString("sex")); } catch (SQLException e) { e.printStackTrace(); } finally {// 每一個關閉語句都要單獨 放 否則一個有異常 會致使其餘資源的關閉 JDBCUtills.close(res, stm, con); } } public static boolean selectByIdName(int id, String name) {// 查詢語句是否存在指定的id 以及 name PreparedStatement psta = null; ResultSet res = null; try { String sql = "select * from t1_user where id = ? and name = ?"; psta = con.prepareStatement(sql);// 建立後再設置參數 psta.setInt(1, id); psta.setString(2, name); res = psta.executeQuery(); // 有數據就返回true 並輸出相對應的信息 if (res.next()) { while (res.next()) System.out.println(res.getInt("id") + "," + res.getString("name")); return true; } else return false; } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtills.close(res, psta, con); } return false; } public static void selectUserByPage(int pageNumber, int pageCount) { PreparedStatement pstm = null; ResultSet res = null; try { String sql = "select * from t1_user limit ? , ?"; pstm = con.prepareStatement(sql); pstm.setInt(1, (pageNumber - 1) * pageCount); pstm.setInt(2, pageCount); res = pstm.executeQuery(); while (res.next()) { System.out.println(res.getInt(1) + "," + res.getString(2) + ","); } } catch (Exception e) { System.out.println(e); } finally { JDBCUtills.close(res, pstm, con); } } }
插入語句的實現代碼
public static void insert(int id , String name , String sex) { PreparedStatement pstm = null; ResultSet res = null; try { String sql = "insert into t1_user(id,name,sex) values(?,?,?)"; pstm = con.prepareStatement(sql); pstm.setInt(1, id); pstm.setString(2, name); pstm.setString(3, sex); int n = pstm.executeUpdate();//受影響的行數 System.out.println(n); }catch(Exception e) { System.out.println("插入失敗"); } finally { JDBCUtills.close(res, pstm, con);; } }
更新代碼的實現
public static void update(int id , String name) { PreparedStatement pstm = null; ResultSet res = null; try { String sql = "update t1_user set name = ? where id = ?"; pstm = con.prepareStatement(sql); pstm.setString(1, name); pstm.setInt(2, id); int n = pstm.executeUpdate(); System.out.println(n); }catch(Exception e ) { System.out.println("更新失敗"); }finally { JDBCUtills.close(res, pstm, con); } }
轉帳操做加事務
public static void transferMoney(int id ,int id1, int money) {//兩個以上的操做數據庫 要加上事務 PreparedStatement pstm = null; PreparedStatement pstm1 = null; ResultSet res = null; try { con.setAutoCommit(false); String sql = "update t1_user set money = money - ? where id = ?"; pstm = con.prepareStatement(sql); pstm.setInt(1, money); pstm.setInt(2, id); pstm.executeUpdate(); ///////////////////////這裏能夠加一段 會報錯的語句 1/0 sql = "update t1_user set money = money + ? where id = ?"; pstm1 = con.prepareStatement(sql); pstm1.setInt(1, money); pstm1.setInt(2, id1); pstm1.executeUpdate(); System.out.println("成功"); con.commit();//提交 若是中間報錯則 回滾數據 }catch(Exception e ) { System.out.println("轉帳失敗"); }finally { JDBCUtills.close(res, pstm1, con); JDBCUtills.close(res, pstm, con); } }
將工具類改寫成鏈接池
public class JDBCUtills { private static ArrayList<Connection> al = new ArrayList<Connection>(); static { for (int i = 0; i < 5; i++) { Connection con = createConn(); al.add(con); } } private static final String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; public static Connection getConn() { if(!al.isEmpty()) { Connection con = al.get(0); al.remove(con); return con;//通常在用完以後就放回去到鏈接池裏面 就在後面那個關閉Connection 那裏加一個歸還操做 } else return createConn(); } private static Connection createConn() { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("輸入登錄帳號"); String user = sc.nextLine(); System.out.println("輸入密碼"); String password = sc.nextLine(); Connection con = null; PreparedStatement pstm = null; ResultSet res = null; try { con = DriverManager.getConnection(url, user, password); System.out.println("登錄成功"); return con; } catch (Exception e) { System.out.println("密碼帳號出錯"); } return con; }
下面把代碼交給dbcp進行管理 運行的時候出現的錯誤: https://blog.csdn.net/anaini1314/article/details/71157791(mysql版本比較新) https://blog.csdn.net/mqs1990/article/details/76167679(缺乏某些第三方庫)
import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbcp2.BasicDataSource; public class dataSource { private static final String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; private static final String user = "root"; private static final String password = "88888888"; private static BasicDataSource ds ; static { ds = new BasicDataSource(); ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setInitialSize(5);//初始化鏈接個數 ds.setMaxTotal(20);//達到二十個不會再建立 只有調用close 纔會歸還對象//能夠用以一個for試試 ds.setMinIdle(4);//最小鏈接 } public static Connection getConnection() { try { return ds.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
c3p0 (雖然差很少 但這個用起來不是很方便)
import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class c3p0dataSource { private static final String url = "jdbc:mysql://localhost:3306/mysql2_1709?serverTimezone=UTC"; private static final String user = "root"; private static final String password = "88888888"; private static ComboPooledDataSource cpds ; static { cpds = new ComboPooledDataSource (); try { cpds.setDriverClass("com.mysql.cj.jdbc.Driver"); cpds.setUser(url); cpds.setUser(user); cpds.setPassword(password); cpds.setInitialPoolSize(5);//初始化鏈接個數 cpds.setMaxPoolSize(20);//達到二十個不會再建立 只有調用close 纔會歸還對象 cpds.setMinPoolSize(4);//最小鏈接 } catch (PropertyVetoException e) { // TODO Auto-generated catch block e.printStackTrace(); } }public static Connection getConnection() { try { return cpds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } }