JDBC入门小记录

JDBC是什么?

Java DataBase Connectivity(Java语言连接数据库)

JDBC的本质是什么?

JDBC是sun公司制定的一套接口(interface)

接口都是调用者和实现者。

面向接口调用,面向接口写实现类,这都属于面向接口编程。

为什么要面向接口编程?

解耦合:降低程序的耦合度,提高程序的扩展了。

多态机制就是非常典型的:面向抽象编程(不要面向具体编程)

为什么SUN制定一天JDBC接口呢?

因为每一个数据库的底层实现原理都不一样。

oracle数据库有自己的原理

MySQL数据库也有自己的原理

每一个数据库产品都有自己独特的实现原理

JDBC的本质是什么?

一套接口


JDBC编程六步

第一步:注册驱动(作用。告诉JAVA程序,即将要连接是哪个品牌的数据库)

第二步:获取连接(表示JVM的进程和数据库进程之间的通道打开了。这属于进程之间的通行,重量级

第三步:获取数据库操作对象(专门执行sql语句的对象)

第四步:执行SQL语句(DQL.DML...)

第五步:处理查询结果集(只有当第四步执行的是select 语句的时候,才有这第五步处理查询结果集)

第六步:释放资源(使用完资源后一定要关闭资源,JAVA和数据库属于进程间的通信,开启之后一定要关闭)

--------------------------------------------------------

http://182.61.200.7:80/index.html

http://通信协议

182.61.200.7 服务器IP地址

80 服务器上软件的端口

index.html 是服务器上的某个资源名


import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
​
​
public class Javares{
public static void main(String[] args){
try{
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
}catch(SQLException e){
e.printStackTrace();
}
}
}

 


从粗糙的连接到慢慢简化

import java.sql.*;
​
public class One{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
DriverManager.registerDriver(new com.mysql.jadbc.Driver());//注册驱动
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls","root","344");//获取连接
stmt = conn.createStatement();//获取数据库操作对象
}catch(SQLException e){
e.printStackTrace();
}finally{
if(stmt !=null){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}

}
if(conn !=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}

}
​
}
​
​
}
​
​
}

慢慢的开始升级

import java.sql.*;
​
public class Two{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);//注册驱动
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls","root","344");//获取连接
stmt = conn.createStatement();//获取数据库操作对象
System.out.println("数据库连接对象 =" + conn);
String sl = "insert into admin(id,username,password)values(5,'赵六','0123')";//执行sql
int index = stmt.executeUpdate(sl);
System.out.println(index == 1?"加入成功":"加入失败");
}catch(SQLException e){
e.printStackTrace();
}finally{//释放资源
try{
if(stmt != null){
stmt.close();
}
}catch
(SQLException e){
e.printStackTrace();
}
try{
if(conn !=null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}

}

}
}
​
​

第3次

import java.sql.*;
​
​
public class Four{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");//注册驱动,用反射来启动类加载
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls","root","344");//获取连接
stmt = conn.createStatement();//获取连接对象
String str = "select id,username,password from admin";//执行SQL
rs = stmt.executeQuery(str);//处理结果集
while(rs.next()){
String id = rs.getString("id");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(id+","+username+","+password);
}
}catch(Exception e){
e.printStackTrace();
}
finally{//释放资源
try{
if(rs !=null){
rs.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(stmt !=null){
stmt.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(conn != null){
conn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}

编写用户登录初级

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
​
public class Zero {
   public static void main(String[] args) {
               Map<String, String> userLoginInfo = initUI();
               boolean loginSuccess = login(userLoginInfo);
               System.out.println(loginSuccess?"登入成功":"登入失败");
​
          }
​
           private static boolean login(Map<String, String> userLoginInfo) {
               boolean loginSuccess = false;
               String username = userLoginInfo.get("username");
               String password = userLoginInfo.get("password");
               Connection conn = null;
               Statement stmt = null;
               ResultSet rs = null;
               try {
                   Class.forName("com.mysql.jdbc.Driver");
                   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "344");
                   stmt = conn.createStatement();
                   String str = "select * from admin where username = '"+username+"' and password = '"+password+"'";
                   rs = stmt.executeQuery(str);
                   if (rs.next()) {
                       loginSuccess = true;
                  }
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   if (rs != null) {
                       try {
                           rs.close();
                      } catch (SQLException e) {
                           e.printStackTrace();
                      }
                  }
                   if (stmt != null) {
                       try {
                           stmt.close();
                      } catch (SQLException e) {
                           e.printStackTrace();
                      }
                  }
                   if (conn != null) {
                       try {
                           conn.close();
                      } catch (SQLException e) {
                           e.printStackTrace();
                      }
                  }
              }
​
​
               return loginSuccess;
          }
​
           private static Map<String, String> initUI () {
               Scanner s = new Scanner(System.in);
               System.out.println("用户名:");
               String username = s.nextLine();
               System.out.println("密码:");
               String password = s.nextLine();
               Map<String, String> userLoginInfo = new HashMap<>();
               userLoginInfo.put("username", username);
               userLoginInfo.put("password", password);
               return userLoginInfo;
          }
​
      }
​

下面有所改动

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
​
public class OneTest {
   public static void main(String[] args) {
       Map<String, String> userLoginInfo = initUI();
       boolean loginSuccess = login(userLoginInfo);
       System.out.println(loginSuccess?"登入成功":"登入失败");
​
  }
​
   private static boolean login(Map<String, String> userLoginInfo) {//将初始化的信息依照数据库进行对比
       boolean loginSuccess = false;//标识
       String username = userLoginInfo.get("username");
       String password = userLoginInfo.get("password");
       Connection conn = null;
       PreparedStatement ps = null;//此处改用PreparedStatement
       ResultSet rs = null;
       try {
           Class.forName("com.mysql.jdbc.Driver");
           conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "344");
           String str = "select * from admin where username = ? and password = ?";//此处把字符串改成问号,然后做下面的处理
           ps = conn.prepareStatement(str);
           ps.setString(1,username);
           ps.setString(2,password);
           rs = ps.executeQuery();
           if (rs.next()) {
               loginSuccess = true;//如果数据库有此数据login为真
          }
      } catch (Exception e) {
           e.printStackTrace();
      } finally {
           if (rs != null) {
               try {
                   rs.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
           if (ps != null) {
               try {
                   ps.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
           if (conn != null) {
               try {
                   conn.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
          }
              }
​
​
               return loginSuccess;//返回值
          }
​
           private static Map<String, String> initUI () {//初始化并返回username,password交给下一步数据库核对
               Scanner s = new Scanner(System.in);
               System.out.println("用户名:");
               String username = s.nextLine();
               System.out.println("密码:");
               String password = s.nextLine();
               Map<String, String> userLoginInfo = new HashMap<>();
               userLoginInfo.put("username", username);
               userLoginInfo.put("password", password);
               return userLoginInfo;
          }
​
      }
​

在一次升级,加上了行级锁处理,保证在处理SQL语句中把事务放在最后提交,而不是自动提交

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
​
public class TwoTest {
   public static void main(String[] args) {
       Connection conn = null;
       PreparedStatement ps = null;
       try {
           Class.forName("com.mysql.jdbc.Driver");
           conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/afreet","root","344");
           conn.setAutoCommit(false);//行级锁处理
           String str = "update bank set money = ? where id = ?";
           ps = conn.prepareStatement(str);
           ps.setDouble(1,10000);
           ps.setInt(2,111);
           int count = ps.executeUpdate();
           ps.setDouble(1,10000);
           ps.setInt(2,222);
           count += ps.executeUpdate();
           System.out.println(count==2?"转账成功":"转账失败");
           conn.commit();//还有这里
      } catch (Exception e) {
           if (conn != null) {
               try {
                   conn.rollback();
              } catch (SQLException e1) {
                   e1.printStackTrace();
              }
          }
           e.printStackTrace();
      }finally {
           if(ps !=null){
               try {
                   ps.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
​
          }
           if(conn !=null){
               try {
                   conn.close();
              } catch (SQLException e) {
                   e.printStackTrace();
              }
​
          }
      }
  }
}
​

最后一段进行封装并且操作

package utils;
​
import java.sql.*;
​
public class DBUtil {
   private DBUtil(){}
   static{
       try {
           Class.forName("com.mysql.jdbc.Driver");
      } catch (ClassNotFoundException e) {
           e.printStackTrace();
      }
  }
​
   public static Connection getConnection() throws SQLException {
       return DriverManager.getConnection("jdbc:mysql://localhost:3306/afreet","root","344");
​
  }
   public static void close(Connection conn, Statement ps, ResultSet rs){
       if (rs != null) {
           try {
               rs.close();
          } catch (SQLException e) {
               e.printStackTrace();
          }
      }
       if (ps != null) {
           try {
               ps.close();
          } catch (SQLException e) {
               e.printStackTrace();
          }
      }
       if (conn != null) {
           try {
               conn.close();
          } catch (SQLException e) {
               e.printStackTrace();
          }
      }
​
      }
​
  }
​
​

以上是封装,下面是封装后的代码

import utils.DBUtil;
​
import java.sql.*;
​
public class Three {
   public static void main(String[] args) {
       Connection conn = null;
       PreparedStatement ps  = null;
       ResultSet rs = null;
       try {
           conn = DBUtil.getConnection();//自定义的封装引用,注册驱动,加上获取连接
           conn.setAutoCommit(false);//行级锁
           String str = "select id,money from bank for update" ;//搜索数据
           ps = conn.prepareStatement(str);//获取连接对象
           rs = ps.executeQuery(str);//操作SQL
           while (rs.next()){
               System.out.println(rs.getString("id")+","+rs.getString("money"));
          }
           conn.commit();//行级锁
      } catch (Exception e) {
           if(conn != null){//
               try {
                   conn.rollback();
              } catch (SQLException e1) {
                   e1.printStackTrace();
              }
          }
           e.printStackTrace();
      }finally{
           DBUtil.close(conn,ps,rs);//引用自定义封装工具
      }
  }
}
​

 

posted @ 2020-09-27 22:05  锁猴  阅读(176)  评论(0)    收藏  举报