JDBC基础总结一

JAVA学习网 2017-10-19 18:15:02

JDBC的概念

通俗的讲,使用java代码(程序)发送sql语句的技术,就是jdbc技术

使用JDBC的前提

登录数据库服务器(连接数据库服务器)

数据库的IP地址

端口

数据库用户名

密码

连接MySQL数据库

day17是一个数据库

需要mysql连接的jar包:mysql-connector-java-5.1.7-bin.jar

代码案例

/**

 * jdbc连接数据库

 */

public class Demo1 {

//连接数据库的URL

private String url = "jdbc:mysql://localhost:3306/day17";

                   // jdbc协议:数据库子协议:主机:端口/连接的数据库   

private String user = "root";//用户名

private String password = "123456";//密码

 

/**

 * (推荐使用这种方式连接数据库)

 * 推荐使用加载驱动程序类  来 注册驱动程序

 * @throws Exception

 */

@Test

public void test3() throws Exception{

 

//通过得到字节码对象的方式加载静态代码块,从而注册驱动程序

Class.forName("com.mysql.jdbc.Driver");

//2.连接到具体的数据库

Connection conn = DriverManager.getConnection(url, user, password);

// con 表示对一个队mysql数据库的连接

System.out.println(conn);  

}

}

 

DDL语句建立表

public class Demo1 {

 

private String url = "jdbc:mysql://localhost:3306/day17";

private String user = "root";

private String password = "123456";

/**

 * 执行DDL语句(创建表)

 */

@Test

public void test1(){

Statement stmt = null;

Connection conn = null;

try {

//1.驱动注册程序

Class.forName("com.mysql.jdbc.Driver");

 

//2.获取连接对象

conn = DriverManager.getConnection(url, user, password);

 

//3.创建Statement

stmt = conn.createStatement();

 

//4.准备sql

String sql = "CREATE TABLE student("+

                   "id INT PRIMARY KEY AUTO_INCREMENT," +

                   "NAME VARCHAR(20)," +

                   "gender VARCHAR(2)" +

                   ")";

 

//5.发送sql语句,执行sql语句,得到返回结果

int count = stmt.executeUpdate(sql);

 

//6.输出

System.out.println("影响了"+count+"行!");

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally{

//7.关闭连接(顺序:后打开的先关闭)

if(stmt!=null)

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

if(conn!=null)

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

}

 

 

JDBC工具类:获取连接,关闭连接

/**

 * jdbc工具类

 *

 */

public class JdbcUtil {

private static String url = null;

private static String user = null;

private static String password = null;

private static String driverClass = null;

 

/**

 * 静态代码块中(只加载一次)

 */

static{

try {

//读取db.properties文件

Properties props = new Properties();

 

InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");

 

//加载文件

props.load(in);

//读取信息

url = props.getProperty("url");

user = props.getProperty("user");

password = props.getProperty("password");

driverClass = props.getProperty("driverClass");

 

 

//注册驱动程序

Class.forName(driverClass);

} catch (Exception e) {

e.printStackTrace();

System.out.println("驱程程序注册出错");

}

}

 

/**

 * 抽取获取连接对象的方法

 */

public static Connection getConnection(){

try {

Connection conn = DriverManager.getConnection(url, user, password);

return conn;

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

 

 

/**

 * 释放资源的方法

 */

public static void close(Connection conn,Statement stmt){

if(stmt!=null){

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

if(conn!=null){

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

 

public static void close(Connection conn,Statement stmt,ResultSet rs){

if(rs!=null)

try {

rs.close();

} catch (SQLException e1) {

e1.printStackTrace();

throw new RuntimeException(e1);

}

if(stmt!=null){

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

if(conn!=null){

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

}

 

 

DML语句 插入数据

@Test

public void testInsert(){

Connection conn = null;

Statement stmt = null;

try {

//通过工具类获取连接对象

conn = JdbcUtil.getConnection();

 

//3.创建Statement对象

stmt = conn.createStatement();

 

//4.sql语句

String sql = "INSERT INTO student(NAME,gender) VALUES('李四','女')";

 

//5.执行sql

int count = stmt.executeUpdate(sql);

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally{

//关闭资源

JdbcUtil.close(conn, stmt);

}

 

 

DML语句 修改数据

@Test

public void testUpdate(){

Connection conn = null;

Statement stmt = null;

//模拟用户输入

String name = "陈六";

int id = 1;

try {

 

//通过工具类获取连接对象

conn = JdbcUtil.getConnection();

 

//3.创建Statement对象

stmt = conn.createStatement();

 

//4.sql语句

String sql = "UPDATE student SET NAME='"+name+"' WHERE id="+id+"";

 

System.out.println(sql);

 

//5.执行sql

int count = stmt.executeUpdate(sql);

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally{

JdbcUtil.close(conn, stmt);

}

}

 

 

DML语句删除数据

@Test

public void testDelete(){

Connection conn = null;

Statement stmt = null;

//模拟用户输入

int id = 1;

try {

//通过工具类获取连接对象

conn = JdbcUtil.getConnection();

 

//3.创建Statement对象

stmt = conn.createStatement();

 

//4.sql语句

String sql = "DELETE FROM student WHERE id="+id+"";

 

System.out.println(sql);

 

//5.执行sql

int count = stmt.executeUpdate(sql);

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally{

JdbcUtil.close(conn, stmt);

}

}

 

DML语句 查询数据

@Test

public void test1(){

Connection conn = null;

Statement stmt = null;

try{

//获取连接

conn = JdbcUtil.getConnection();

//创建Statement

stmt = conn.createStatement();

//准备sql

String sql = "SELECT * FROM student";

//执行sql

ResultSet rs = stmt.executeQuery(sql);

//遍历结果

while(rs.next()){

int id = rs.getInt("id");

String name = rs.getString("name");

String gender = rs.getString("gender");

System.out.println(id+","+name+","+gender);

}

}catch(Exception e){

e.printStackTrace();

throw new RuntimeException(e);

}finally{

JdbcUtil.close(conn, stmt);

}

}

 

 

使用PreparedStatement执行sql语句

插入数据

@Test

public void testUpdate() {

Connection conn = null;

PreparedStatement stmt = null;

try {

//1.获取连接

conn = JdbcUtil.getConnection();

 

//2.准备预编译的sql

String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符

 

//3.执行预编译sql语句(检查语法)

stmt = conn.prepareStatement(sql);

 

//4.设置参数值

/**

 * 参数一: 参数位置  从1开始

 */

stmt.setString(1, "王五");

stmt.setInt(2, 9);

 

//5.发送参数,执行sql

int count = stmt.executeUpdate();

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

JdbcUtil.close(conn, stmt);

}

}

 

修改数据

@Test

public void testUpdate() {

Connection conn = null;

PreparedStatement stmt = null;

try {

//1.获取连接

conn = JdbcUtil.getConnection();

 

//2.准备预编译的sql

String sql = "UPDATE student SET NAME=? WHERE id=?"; //?表示一个参数的占位符

 

//3.执行预编译sql语句(检查语法)

stmt = conn.prepareStatement(sql);

 

//4.设置参数值

/**

 * 参数一: 参数位置  从1开始

 */

stmt.setString(1, "王五");

stmt.setInt(2, 2);

 

//5.发送参数,执行sql

int count = stmt.executeUpdate();

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

JdbcUtil.close(conn, stmt);

}

}

 

 

删除数据

@Test

public void testDelete() {

Connection conn = null;

PreparedStatement stmt = null;

try {

//1.获取连接

conn = JdbcUtil.getConnection();

 

//2.准备预编译的sql

String sql = "DELETE FROM student WHERE id=?"; //?表示一个参数的占位符

 

//3.执行预编译sql语句(检查语法)

stmt = conn.prepareStatement(sql);

 

//4.设置参数值

/**

 * 参数一: 参数位置  从1开始

 */

stmt.setInt(1, 6);

 

//5.发送参数,执行sql

int count = stmt.executeUpdate();

 

System.out.println("影响了"+count+"行");

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

JdbcUtil.close(conn, stmt);

}

}

 

查询数据

@Test

public void testQuery() {

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try {

//1.获取连接

conn = JdbcUtil.getConnection();

 

//2.准备预编译的sql

String sql = "SELECT * FROM student";

 

//3.预编译

stmt = conn.prepareStatement(sql);

 

//4.执行sql

rs = stmt.executeQuery();

 

//5.遍历rs

while(rs.next()){

int id = rs.getInt("id");

String name = rs.getString("name");

String gender = rs.getString("gender");

System.out.println(id+","+name+","+gender);

}

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

//关闭资源

JdbcUtil.close(conn,stmt,rs);

}

}

 

 

PreparedStatement vs Statment

1)语法不同:PreparedStatement可以使用预编译的sql,而Statment只能使用静态的sql

2)效率不同: PreparedStatement可以使用sql缓存区,效率比Statment

3)安全性不同: PreparedStatement可以有效防止sql注入,而Statment不能防止sql注入。

 

推荐使用PreparedStatement

 

防止数据库漏洞

 

 

 

public class Demo2 {

//模拟用户输入

private String name = "ericdfdfdfddfd' OR 1=1 -- ";

// private String name = "eric";

private String password = "123456dfdfddfdf";

// private String password = "123456";

 

/**

 * Statment存在sql被注入的风险

 */

@Test

public void testByStatement(){

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

//获取连接

conn = JdbcUtil.getConnection();

 

//创建Statment

stmt = conn.createStatement();

 

//准备sql

String sql = "SELECT * FROM users WHERE NAME='"+name+"' AND PASSWORD='"+password+"'";

System.out.println(sql);

 

//执行sql

rs = stmt.executeQuery(sql);

 

if(rs.next()){

//登录成功

System.out.println("登录成功");

}else{

System.out.println("登录失败");

}

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

JdbcUtil.close(conn, stmt ,rs);

}

 

}

 

/**

 * PreparedStatement可以有效地防止sql被注入

 */

@Test

public void testByPreparedStatement(){

Connection conn = null;

PreparedStatement stmt = null;

ResultSet rs = null;

try {

//获取连接

conn = JdbcUtil.getConnection();

 

String sql = "SELECT * FROM users WHERE NAME=? AND PASSWORD=?";

 

//预编译

stmt = conn.prepareStatement(sql);

 

//设置参数

stmt.setString(1, name);

stmt.setString(2, password);

 

//执行sql

rs = stmt.executeQuery();

 

if(rs.next()){

//登录成功

System.out.println("登录成功");

}else{

System.out.println("登录失败");

}

 

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

JdbcUtil.close(conn, stmt ,rs);

}

 

}

}

 

JDBC核心的API(类和方法)

|- DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序

|-registerDriver(driver)  : 注册驱动类对象

|-Connection getConnection(url,user,password);  获取连接对象

 

|- Connection接口: 表示java程序和数据库的连接对象。

|- Statement createStatement() : 创建Statement对象

|- PreparedStatement prepareStatement(String sql)  创建PreparedStatement对象

|- CallableStatement prepareCall(String sql) 创建CallableStatement对象

 

|- Statement接口: 用于执行静态的sql语句

|- int executeUpdate(String sql)  : 执行静态的更新sql语句(DDLDML

|- ResultSet executeQuery(String sql)  :执行的静态的查询sql语句(DQL

 

|-PreparedStatement接口:用于执行预编译sql语句

|- int executeUpdate() : 执行预编译的更新sql语句(DDLDML

|-ResultSet executeQuery()  : 执行预编译的查询sql语句(DQL

 

|-CallableStatement接口:用于执行存储过程的sql语句(call xxx

|-ResultSet executeQuery()  : 调用存储过程的方法

 

|- ResultSet接口:用于封装查询出来的数据

|- boolean next() : 将光标移动到下一行

|-getXX() : 获取列的值

 

 

阅读(789) 评论(0)