JDBC链接Mysql数据库
来源:互联网 发布:ubuntu删除用户 编辑:程序博客网 时间:2024/04/29 03:59
JDBC是Java访问关系型数据库的规则
1.驱动的原理及使用
是JDBC这个规则在具体数据库中的实现类,且用Java书写(需要安装JDK7)
2.做JDBC代码,需要用到如下几个固定的步骤【查询】为例:
1_注册MySQL数据库服务器的驱动,DriverManager
2_获取MySQL数据库服务器的连接,Connection
3_获取封装SQL语句的对象,Statemnet
4_执行这个SQL语句,并返回结果集合,ResultSet
5_迭代这个结果集合,while(){}
6_按轻到重的原则立即关系连接对象,ResultSet->Statement-Connection,在必要情况下,可重用Connection
抽取工具类封装获取链接数据库,关闭链接的方法,直接调用即可
/** * 1_工具类必须是final * 2_不能new工具类 * 3_所有的方法public static */public final class JdbcUtils { private static String driver; private static String url; private static String user; private static String password; static{ InputStream is = null; try { //读取db.properties属性文件中的内容 //获取JdbcUtils的类加载器 ClassLoader cl = JdbcUtils.class.getClassLoader(); //通过类加载器得到InputStream对象 //参数一:db.properties在src中的类路径,即src下面的路径 is = cl.getResourceAsStream("cn/itheima/config/db.properties"); Properties props = new Properties(); props.load(is); //根据key找到value driver = props.getProperty("mysql.driver"); url = props.getProperty("mysql.url"); user = props.getProperty("mysql.user"); password = props.getProperty("mysql.password"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("加载db.properties文件失败"); } finally{ if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); }finally{ is = null; } } } } static{ try { //注册MySQL数据库服务器驱动 Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } } private JdbcUtils(){} public static Connection getConnection(){ try { return DriverManager.getConnection(url,user,password); } catch (SQLException e) { throw new RuntimeException(e); } } public static void close(ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally{ rs = null; } } } public static void close(Statement stmt){//多态 if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally{ stmt = null; } } } public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally{ conn = null; } } }}
3.DriverManager(类)、Connection(接口)、Statement(接口)、ResultSet(接口)详细使用
DriverManager:
它是一个类,由原SUN公司提供,负责管理一个或一组访问具体数据库的驱动,
即你想访问Oracle数据库服务器的话,就让DriverManager加载Oracle驱动,
只需注册一次就行
Connection:
是原SUN公司提供的接口,是属于重量级对象,建议少创建,要重用
只要你想与数据库进行操作,必须获取连接对象
jdbc:mysql://127.0.0.1:3306/jdbc”,”root”,”root”
jdbc:主协议,你只要使用jdbc技术访问数据库,都是jdbc主协议
mysql:子协议
127.0.0.1:MySQL数据库服务器所在PC的IP地址或域名,建议用IP
3306:MySQL数据库服务器所在的PC的端口号
jdbc:访问数据库服务器中哪一个具体的数据库
root:用户名
root:密码,如果没有密码的话,也需要写”“空字符串
Statement:
负责封装SQL语句并执行的对象,是原SUN公司提供的接口
SQL语句在JDBC中分为二大类
1_静态SQL:SQL语句中无?符号,即select id,name from users where name = ‘..’
2_动态SQL:SQL语句中有?符号,即select id,name from users where name = ?
?号由程序在运行时动态设置的值
Statement常用的API:
查询:executeQuery(参数为静态SQL),返回值为ResultSet
增删改:executeUpdate(参数为静态SQL),返回值为Int
ResultSet:
负责装查询语句的结果,默认情况下,游标位于第一条记录的前边。
next()方法就能向下移动一行,如果有结果,返回true
4.JDBC的CURD操作
增删改:Statmenet.executeUpdate(),返回值为int,表示这次操作影响了表中的几条记录
查询:Statment.executeQuery(),返回值为ResultSet,表示这次查询操作结果记录数形成的集合
5.防止SQL注入及PrepareStatement使用
客户端利用JDBC-【Statement】的缺点,传入非法的参数,从而让JDBC返回不合法的值,
这种情况下,统称为SQL注入。
现在项目中都不直接用Statement了,而用PreparedStatement。
PreparedStatement它除了具有Statement是所有功能外,
还有动态SQL处理能力,包括:程序执行时动态为?符号设置值,安全检查,避免SQL注入问题,预处理能力。
Statement只能处理静态SQL
PreparedStatement既能处理静态SQL,又能处理动态SQL,它继承了Statement的特点
站在预处理这个角度来说的:
PreparedStatement【适合】做连续多次相同结构的SQL语句,有优势。
Statement【适合】做连续多次不相同结构的SQL语句,有优势。
/** * PreparedStatement完成对users表的CURD操作 */public class Demo01 { /** * 增加用户 */ public void add(User user){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into users(username,gender,hiredate) values(?,?,?)"; try{ conn = JdbcUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1,user.getUsername()); pstmt.setString(2,user.getGender()); pstmt.setDate(3,new java.sql.Date(user.getHiredate().getTime())); int i = pstmt.executeUpdate(); System.out.println(i>0?"成功":"失败"); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("增加用户失败"); }finally{ JdbcUtils.close(rs); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } /** * 修改用户 */ public void update(String oldUsername,String newUsername){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "update users set username = ? where username = ?"; try{ conn = JdbcUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1,newUsername); pstmt.setString(2,oldUsername); int i = pstmt.executeUpdate(); System.out.println(i>0?"成功":"失败"); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("增加用户失败"); }finally{ JdbcUtils.close(rs); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } /** * 查询用户 * @param lastname 在这里表示姓 * @param gender 性别 */ public void find(String lastname,String gender){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; //String sql = "select * from users where username like '赵%' and gender = '男'"; String sql = "select id,username,gender,hiredate from users where username like ? and gender = ?"; try{ conn = JdbcUtils.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1,lastname+"%"); pstmt.setString(2,gender); rs = pstmt.executeQuery(); while(rs.next()){ int id = rs.getInt("id"); String username = rs.getString("username"); gender = rs.getString("gender"); java.sql.Date hiredate = rs.getDate("hiredate"); System.out.println(id+"#"+username+"#"+gender+"#"+hiredate); } }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("查询用户 失败"); }finally{ JdbcUtils.close(rs); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } /** * 批量删除用户 */ public void delete(int... ids){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; StringBuffer sb = new StringBuffer("delete from users where id in ("); for(int id : ids){ sb.append(id+","); } //删除最后一个逗号 sb.deleteCharAt(sb.length()-1); //在最后拼接) sb.append(")"); String sql = sb.toString(); try{ conn = JdbcUtils.getConnection(); pstmt = conn.prepareStatement(sql); int i = pstmt.executeUpdate(); System.out.println(i>0?"成功":"失败"); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException("批量删除用户失败"); }finally{ JdbcUtils.close(rs); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } public static void main(String[] args) { Demo01 test = new Demo01(); User user = new User(); test.delete(1,6,7); }}
总结:抽取方法封装成工具类的思想值得学习,将繁琐的过程直接调用方法即可;
- JDBC链接Mysql数据库
- jdbc链接mysql数据库
- JDBC链接mysql数据库
- jdbc链接mysql数据库
- 使用jdbc链接mysql数据库
- 通过JDBC链接Mysql数据库
- jdbc链接mysql数据库代码
- JDBC数据库链接(MySQL数据库连接)
- JAVA --JDBC链接mysql数据库
- java jdbc链接mysql数据库
- java链接mysql数据库-jdbc
- 使用JDBC链接MYSQL数据库
- Java jdbc 链接数据库MYSQL问题
- JDBC 链接Mysql 数据库详细实例
- java通过JDBC链接Mysql数据库
- Java链接MySQL数据库配置(JDBC)
- Android:使用JDBC链接MySQL数据库
- java+JDBC链接MySQL数据库操作
- 七元组
- 保活、心跳机制
- MFCC中CString, int, string, char之间的转换
- telnet - 远程终端协议
- 4 如何依次对准多个点云图像(未完待续)
- JDBC链接Mysql数据库
- muduo库的BlockingQueue和BoundBlockingQueue类剖析
- tlv - 可变编码格式
- Linux基础命令 ls
- serial interface - 串行接口
- 2016年的最后一个月,重新出发
- hdu1856 More is better 并查集
- snmp - 简单网络管理协议
- rj45 - 双绞线以太网端口