jdbc一般步骤

本文详细介绍了使用 Java 原生 JDBC 进行数据库操作的基本步骤,包括加载驱动、获取连接、执行 SQL 语句及处理结果集等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 原生JDBC操作数据库,是比较常见的面试题,所以一定要牢牢掌握住。

记住一般步骤,就好写代码了。

1、Class.forName()加载数据库连接驱动。

2、DriverManager.getConnection()获取数据连接对象。

3、根据SQL语句获取会话对象,会话对象一般用PreparedStatement类型,conn.prepareStatement(),注意方法名和类名不一样哟。

4、执行SQL处理结果集,执行SQL前如果有参数值就设置参数值setXXX()。

5、关闭结果集、关闭会话、关闭连接。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lcx.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8. import java.sql.Savepoint;  
  9. import java.util.Properties;  
  10.   
  11. public class Test {  
  12.     public static void main(String[] args) {  
  13.         String url1="jdbc:mysql://localhost:3306/JAVA?user=root&password=root&useUnicode=true&charactorEncoding=UTF8";  
  14.         String url2="jdbc:mysql://localhost:3306/JAVA?useUnicode=true&charactorEncoding=UTF8";  
  15.         String url3="jdbc:mysql://localhost:3306/JAVA";  
  16.         String user="root";  
  17.         String password="root";  
  18.         Connection conn3 = null;  
  19.         Savepoint point1 = null;  
  20.           
  21.         try {  
  22.             //1、加载数据库驱动,包名一般为域名反写  
  23.             Class.forName("com.mysql.jdbc.Driver");  
  24.             Properties info = new Properties();  
  25.             info.put("user""root");  
  26.             info.put("password""root");  
  27.             info.put("useUnicode","true");  
  28.             info.put("charactorEncoding","utf8");  
  29.             /* 
  30.              * 2、获取数据连接对象,DriverManager.getConnection方法有3个重载方法 
  31.              */  
  32. //          Connection conn1 = DriverManager.getConnection(url3, user, password);//将连接的用户名、密码放到方法参数中  
  33. //          Connection conn2 = DriverManager.getConnection(url2,info);//将连接的属性键值对放在Properties对象中  
  34.             conn3 = DriverManager.getConnection(url1);//将所有连接信息都放在URL中  
  35.             /* 
  36.              * 3、根据SQL获取sql会话对象,有2种方式 Statement、PreparedStatement 
  37.              *      1、 PreparedStatement接口继承Statement, PreparedStatement 实例包含已编译的 SQL 语句,所以其执行速度要快于 Statement 对象。 
  38.              *      2、作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能。三种方法  execute、 executeQuery 和 executeUpdate 已被更改以使之不再需要参数 
  39.              *      3、在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替 Statement.也就是说,在任何时候都不要使用Statement. 
  40.              *          一.代码的可读性和可维护性.Statement需要不断地拼接,而PreparedStatement不会。 
  41.              *          二.PreparedStatement尽最大可能提高性能.DB有缓存机制,相同的预编译语句再次被调用不会再次需要编译。 
  42.              *          三.最重要的一点是极大地提高了安全性.Statement容易被SQL注入,而PreparedStatementc传入的内容不会和sql语句发生任何匹配关系。 
  43.              * 最常用的api 
  44.              * addBatch()/addBatch(String sql) 预编译SQL语句,只编译一回哦,效率高啊。剥瓜子,一个一个剥,最后一口吃。 
  45.              * setXXX(parameterIndex,value) 设置指定参数的值。 
  46.              * execute()  执行 SQL 语句,该语句可以是任何种类的 SQL 语句。 
  47.              * executeQuery() 执行查询语句返回ResultSet 
  48.              * executeUpdate() 执行增删改,返回影响的行数。 
  49.              *  
  50.              */  
  51.             String sql_other = "TRUNCATE TABLE t_user_info";  
  52.             String sql_insert = "insert into t_user_info(id,user,sex,age) value(null,?,?,?)";  
  53.             String sql_query = "select * from t_user_info where id < ?";  
  54.             conn3.setAutoCommit(false);//关闭自动提交  
  55.             PreparedStatement preparedStatement_other = conn3.prepareStatement(sql_other);  
  56.             PreparedStatement preparedStatement_insert = conn3.prepareStatement(sql_insert);  
  57.             PreparedStatement preparedStatement_query = conn3.prepareStatement(sql_query);  
  58.             preparedStatement_other.execute();  
  59.               
  60.               
  61.             for(int i=0;i<100;i++){  
  62.                 preparedStatement_insert.setString(1"user_"+i);  
  63.                 preparedStatement_insert.setString(2"n");  
  64.                 preparedStatement_insert.setInt(3, i);  
  65.                 if(i>50){  
  66. //                  preparedStatement_insert.setString(3, "我是错误的尝试");  
  67.                 }  
  68.                 preparedStatement_insert.addBatch();  
  69.             }  
  70.             //一次性插入100条记录,如果中间有出错,那么这一次性的插入都不会成功  
  71.             int[] updateInt = preparedStatement_insert.executeBatch();  
  72.             conn3.commit();  
  73.             point1 = conn3.setSavepoint("point1");  
  74.             System.out.println(updateInt.length);  
  75.               
  76.             preparedStatement_query.setInt(150);  
  77.             //4、执行SQL语句,查询语句就获取结果集  
  78.             ResultSet result = preparedStatement_query.executeQuery();  
  79.             while(result.next()){  
  80.                 int a = result.getInt("id");  
  81.                 int b = result.getInt(1);  
  82.                 System.out.println("第一列值,通过列名:"+a+",通过下标:"+b);  
  83.                   
  84.             }  
  85.             /* 
  86.              * 5、关闭结果集、关闭会话、关闭连接 
  87.              */  
  88.             result.close();  
  89.             preparedStatement_other.close();  
  90.             preparedStatement_insert.close();  
  91.             preparedStatement_query.close();  
  92.             conn3.close();  
  93.               
  94.         } catch (ClassNotFoundException e) {  
  95.             System.out.println("驱动没有加载到。。。");  
  96.             e.printStackTrace();  
  97.         } catch (SQLException e) {  
  98.             System.out.println("出现sql异常。。。");  
  99.             try {  
  100.                 conn3.rollback(point1);;  
  101.             } catch (SQLException e1) {  
  102.                   
  103.                 e1.printStackTrace();  
  104.             }  
  105.             e.printStackTrace();  
  106.         }  
  107.     }  
  108. }  
JDBC 进一步封装

我们将获取连接和释放连接封装到工具类中,执行SQL的感觉没有必要封装,这样更灵活。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lcx.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7. import java.sql.Statement;  
  8.   
  9. public class JDBCUtil {  
  10.     /** 
  11.      * jdbc:mysql://主机名称:连接端口/数据库的名称?参数=值 
  12.      * String url = "jdbc:mysql://localhost:3306/JAVA?user=root&password=root&useUnicode=true&characterEncoding=UTF8"; 
  13.      * 也可在获取连接的时候使用用户名和密码 
  14.      * 避免中文乱码要指定useUnicode和characterEncoding, 执行数据库操作之前要在数据库管理系统上创建一个数据库,名字自己定, 
  15.      */  
  16.     private static final String url="jdbc:mysql://localhost:3306/JAVA";  
  17.     private static final String user="root";  
  18.     private static final String password="root";  
  19.     private static Connection conn;  
  20.     //静态代码块,类加载时就加载驱动  
  21.     static {  
  22.         //1、加载驱动  
  23.         try {  
  24.             Class.forName("com.mysql.jdbc.Driver");  
  25.         } catch (ClassNotFoundException e) {  
  26.             System.out.println("Exception: com.mysql.jdbc.driver not found Exception");  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30.     private JDBCUtil(){  
  31.           
  32.     }  
  33.     //2获取连接的方法,只产生一个连接  
  34.     public static Connection getConnection(){  
  35.         try {  
  36.             if(conn==null){  
  37.                 synchronized (JDBCUtil.class) {  
  38.                     if(conn==null){  
  39.                         conn = DriverManager.getConnection(url, user, password);  
  40.                     }  
  41.                 }  
  42.             }  
  43.         } catch (SQLException e) {  
  44.             System.out.println("Exception: get mysql connection Exception");  
  45.             e.printStackTrace();  
  46.         }  
  47.         return conn;  
  48.     }  
  49.     //最后释放资源,中间操作由preparedStatement 去操作更灵活  
  50.     public static void free(ResultSet result,Statement statement,Connection connection){  
  51.         try {  
  52.             if(result!=null){//关闭结果集  
  53.                 result.close();  
  54.             }  
  55.         } catch (SQLException e) {  
  56.             e.printStackTrace();  
  57.         }finally{  
  58.             try {  
  59.                 if(statement!=null){//关闭statement会话  
  60.                     statement.close();  
  61.                 }  
  62.             } catch (SQLException e) {  
  63.                 e.printStackTrace();  
  64.             }finally{  
  65.                 try {  
  66.                     if(connection!=null){  
  67.                         connection.close();//关闭连接  
  68.                     }  
  69.                 } catch (SQLException e) {  
  70.                     e.printStackTrace();  
  71.                 }  
  72.             }  
  73.               
  74.         }  
  75.           
  76.     }  
  77. }  

使用工具类操作数据处理

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lcx.test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7.   
  8. public class JDBCTest {  
  9.   
  10.     public static void main(String[] args) {  
  11.         //1、加载驱动、获取连接  
  12.         Connection connection = JDBCUtil.getConnection();  
  13.         String sql_init ="TRUNCATE TABLE t_user_info";  
  14.         String sql_insert = "insert into t_user_info(id,user,sex,age) value(null,?,?,?)";  
  15.         String sql_query = "select * from t_user_info where id < ?";  
  16.         PreparedStatement ps_init;  
  17.         PreparedStatement ps_insert;  
  18.         PreparedStatement ps_query;  
  19.         try {  
  20.             connection.setAutoCommit(false);  
  21.             //2、根据sql语句获取 获取预编译语句对象  
  22.             ps_init = connection.prepareStatement(sql_init);  
  23.             ps_insert = connection.prepareStatement(sql_insert);  
  24.             ps_query = connection.prepareStatement(sql_query);  
  25.               
  26.             ps_init.execute();//可以执行任何种类的SQL语句  
  27.             //3、有参数值,就设置参数值,然后执行预编译语句,获取结果集  
  28.             for(int i=0;i<100;i++){  
  29.                 ps_insert.setString(1"user_"+i);  
  30.                 ps_insert.setString(2"n");  
  31.                 ps_insert.setInt(3, i);  
  32.                 ps_insert.addBatch();//增加的批处理队列中  
  33.             }  
  34.             ps_insert.executeBatch();//一次性执行  
  35.               
  36.             ps_query.setInt(150);  
  37.             //查询记录,获取结果集  
  38.             ResultSet result = ps_query.executeQuery();  
  39.             while(result.next()){  
  40.                 int a = result.getInt("id");  
  41.                 int b = result.getInt(1);  
  42.                 System.out.println("第一列通过列明:"+a+",第一列通过index:"+b);  
  43.             }  
  44.             connection.commit();  
  45.             //5、释放资源  
  46.             JDBCUtil.free(result, ps_query, connection);  
  47.             JDBCUtil.free(result, ps_init, connection);  
  48.             JDBCUtil.free(result, ps_insert, connection);  
  49.         } catch (SQLException e) {  
  50.             try {  
  51.                 connection.rollback();  
  52.             } catch (SQLException e1) {  
  53.                 e1.printStackTrace();  
  54.             }  
  55.             e.printStackTrace();  
  56.         }  
  57.           
  58.     }  
  59.   
  60. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值