JDBC 程序编写步骤
1.注册驱动-加载Driver 类
2.获取连接-得到Connection
3.执行增删改查-发送SQL给mysql执行
4.释放资源-关闭相关连接
连接数据库5种方式
连接数据库方式一
Driver driver = new Driver();
//(1)jdbc:mysql://规定好表示协议,通过jdbc的方式连接mysql
//(2)localhost 主机,可以是ip地址
//(3)3306 表示mysql监听的端口
//(4)hsp_db02 连接到mysql dbms 的哪个数据库
//(5)mysql的连接本质就是前面学过的socket连接
String url = "jdbc:mysql://localhost:3306/数据库名字";
String url = "jdbc:mysql://localhost:3306/jdbc";
//将用户名和密码放入到Properties对象
Properties properties = new Properties();
//说明user和password 是规定好,后面的值根据实际情况写
properties.setProperty("user","root"); //用户
properties.setProperty("password","123456");//密码
Connection connection = driver.connect(url,properties);
String sql = "delete from actor where id='1'";
//statement 用于执行静态SQL语句并返回其生成的结果的对象
Statement statement = connection.createStatement();
int rows = statement.executeUpdate(sql);//如果是 dml语句,返回的就是影响行数
System.out.println(rows>0?"成功":"失败");
statement.close();
connection.close();
不关闭会影响其他操作数据库
连接数据库方式二
//使用反射加载Driver类,动态加载,更加的灵活,减少依赖性
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/jdbc";
Properties properties = new Properties();
properties.setProperty("user","root"); //用户
properties.setProperty("password","123456");//密码
Connection connection = driver.connect(url,properties);
System.out.println("方式2"+connection);
connection.close();
连接数据库方式三
//使用DriverManager替代Diver 进行统一管理
//使用反射加载Driver
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url和user和password
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
DriverManager.registerDriver(driver);//注册Driver驱动
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println("方式3"+connection);
连接数据库方式四
//使用Class.forName 自动完成注册驱动,简化代码
//使用反射加载Driver
//在加载 Driver类时,完成注册
/*
源码:
1.静态代码块,在类加载时,会执行一次。
2.DriverManager.registerDriver(new Driver());
3.因此注册driver的工作已经完成
static {
try {
DriverManager.registerDriver(new Driver());}catch(SQLException var1){
throw new RuntimeException("Can't register driver!");
*/
Class.forName("com.mysql.jdbc.Driver");
//创建url和user和password
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println("方式4"+connection);
1、mysqL驱动5.1.6可以无需CLass .forName(“com.mysql.jdbc.Driver”);
2、从jdk1.5以后使用了jdbc4,不再需要显示调用class.forName()注册驱动而是自动调用驱动jar包下META-INF\services\java .sql.Driver文本中的类名称去注册
连接数据库方式五
//在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
Class.forName("com.mysql.jdbc.Driver");//建议写上
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println("方式5"+connection);
ResultSet[结果集]
1、表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
2、ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
3、next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");//建议写上
//2.得到连接
Connection connection = DriverManager.getConnection(url,user,password);
//3.得到Statement
Statement statement = connection.createStatement();
//4.组织sqL
String sql = "select id,name,sex,borndate,phone from actor";
//执行给定的SQL语句,该语句返回单个ResultSet对象
java.sql.ResultSet resultSet = statement.executeQuery(sql);
//5.使用while取出数据
while(resultSet.next()){
//让光标向后移动,如果没有更多行,则返回false
int id = resultSet.getInt(1);//获取该行的第1列
String name = resultSet.getString(2);//获取该行的第2列
String sex = resultSet.getString(3);//获取该行的第3列
Date date = resultSet.getDate(4);//获取该行的第4列
String phone = resultSet.getString(5);//获取该行的第5列
System.out.println(id + "\t" + name + "\t" + sex + "\t" + date + "\t" + phone);
}
//6.关闭连接
resultSet.close();
statement.close();
connection.close();
previous() 向上移动一行
getXxx(列的索引 列名)
getObject(列的索引 列名)返回对应列的值,接收类型为Object
Statement
1、Statement对象 用于执行静态SQL语句并返回其生成的结果的对象
2、在连接建立后,需要对数据库进行访问,执行 命名或是SQL语句,可以通过
Statement[存在SQL注入]
如果账号输入1' or,密码输入:or '1'='1还是能查询成功
PreparedStatement「预处理]
CallableStatement[存储过程]
3、Statement对象执行SQL语句,存在SQL注入风险
4、SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的 SQL语句段或命令,恶意攻击数据库。sql injection.sql
5、要防范 SQL 注入,只要用 PreparedStatement(从Statement扩展而来) 取代 Statement 就可以了
Scanner scanner = new Scanner(System.in);
//让其输入名字
System.out.println("请输入查询的姓名");
//next():当接收到空格或者'就是表示结束
//如果希望看到SQL注入,这里需要用nextLine
String query_name = scanner.nextLine();
System.out.println("请输入查询的性别");
String query_sex = scanner.nextLine();
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");//建议写上
//2.得到连接
Connection connection = DriverManager.getConnection(url,user,password);
//3.得到Statement
java.sql.Statement statement = connection.createStatement();
//4.组织sqL
String sql = "select id,name,sex,borndate,phone from actor where name='"+query_name+"'and sex='"+query_sex+"'";
//执行给定的SQL语句,该语句返回单个ResultSet对象
java.sql.ResultSet resultSet = statement.executeQuery(sql);
//如果查询到一条记录,则说明该管理存在
if (resultSet.next()){
System.out.println("恭喜!!!查询成功");
}else {
System.out.println("查询失败!!!");
}
//6.关闭连接
resultSet.close();
statement.close();
connection.close();
PreparedStatement
1、PreparedStatement 执行的 SQL 语句中的参数用问号(?)来表示,调用PreparedStatement 对象的 setXxx()方法来设置这些参数.setXxx()方法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从1开始),第二个是设置的 SQL 语句中的参数的值
2、调用 executeQuery(),返回 ResultSet 对象
3、调用 executeUpdate():执行更新,包括增、删、修改
预处理好处
1、不再使用+拼接sql语句,减少语法错误
2、有效的解决了sql注入问题
3、大大减少了编译次数,效率较高
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;
public class PreparedStatement {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
//让其输入名字
System.out.println("请输入查询的姓名");
//next():当接收到空格或者'就是表示结束
//如果希望看到SQL注入,这里需要用nextLine
String query_name = scanner.nextLine();
System.out.println("请输入查询的性别");
String query_sex = scanner.nextLine();
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");//建议写上
//2.得到连接
Connection connection = DriverManager.getConnection(url,user,password);
//3.得到PreparedStatement
//3.1 组织SqL,Sql语的?就相当于占位符
String sql = "select id,name,sex,borndate,phone from actor where name=? and sex=?";
//3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
java.sql.PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3给?赋值
preparedStatement.setString(1,query_name);
preparedStatement.setString(2,query_sex);
//执行给定的SQL语句,该语句返回单个ResultSet对象
//执行 select 语句使用 executeQuery
//如果执行的是 dml(update,insert delete)executeUpdate()
//这里执行executeQuery,不要在写 sql
java.sql.ResultSet resultSet = preparedStatement.executeQuery();
//如果查询到一条记录,则说明该管理存在
if (resultSet.next()){
System.out.println("恭喜!!!查询成功");
}else {
System.out.println("查询失败!!!");
}
//6.关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;
public class PreparedStatementDML {
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
//让其输入名字
System.out.println("请输入查询的姓名");
//next():当接收到空格或者'就是表示结束
//如果希望看到SQL注入,这里需要用nextLine
String query_name = scanner.nextLine();
System.out.println("请输入查询的性别");
String query_sex = scanner.nextLine();
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");//建议写上
//2.得到连接
Connection connection = DriverManager.getConnection(url,user,password);
//3.得到PreparedStatement
//3.1 组织SqL,Sql语的?就相当于占位符
//添加记录
//String sql = "insert into actor values (null,?,?,borndate=2000-09-19,phone=110)";
//修改记录
//String sql = "update actor set borndate='2000-09-19' where name=?";
//删除记录
String sql = "delete from actor where name=?and sex=?";
//3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
java.sql.PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3给?赋值
preparedStatement.setString(1,query_name);
preparedStatement.setString(2,query_sex);
//4.执行 dml 语句使用executeQuery
int rows = preparedStatement.executeUpdate();
System.out.println(rows>0?"成功":"失败");
//关闭连接
preparedStatement.close();
connection.close();
}
}
execute()执行任意sql,返回布尔
setXxx(占位符索引,占位符的值),解决SQL注入
setObject(占位符索引, 占位符的值)
封装JDBCUtils工具类
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
//这是一个工具类,完成 mysql的连接和关闭资源
public class JDBCUtils {
//定义相关的属性(4个),因为只需要一份,因此,我们做出static
private static String user;//用户名
private static String password;//密码
private static String url;//url
private static String driver;//驱动名
//在static代码块去初始化
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//读取相关的属性值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
//在实际开发中,我们可以这样处理
//在实际开发中,我们可以这样处理
//1.将编译异常转成运行异常
//2.这是调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便
throw new RuntimeException(e);
}
}
//连接数据库,返回Connection
public static Connection getConnection(){
try{
return DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
//1.将编译异常转成运行异常
//2.调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便。
throw new RuntimeException(e);
}
}
//关闭相应资源
/*
1.ResultSet 结果集
2.Statement 或者PreparedStatement
* 3.Connection
4.如果需要关闭资源,就传入对象,否则传入nuLl
*/
public static void close(ResultSet resultSet, Statement statement,Connection connection){
//判断是否为null
try {
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
//将编译异常转成运行异常抛出
throw new RuntimeException(e);
}
}
}
简单使用JDBCUtils工具类
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
//该类演示如何使用IDBCUtils工具类,完成dml和select
public class JDBCUtils_Use {
@Test
public void testSelect(){
//1、得到连接
Connection connection = null;
//2.组织一个sql
String sql = "select * from actor";
//3.创建PreparedStatement 对象
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//执行 得到结果集
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String sex = resultSet.getString("sex");
Date date = resultSet.getDate("borndate");
String phone = resultSet.getString("phone");
System.out.println(id +"\t"+name+"\t"+sex+"\t"+date+"\t"+phone);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(resultSet,preparedStatement,connection);
}
}
@Test
//insert,update,delete
public void testDML(){
//1、得到连接
Connection connection = null;
//2.组织一个sql
String sql = "update actor set name=? where id=?";
//3.创建PreparedStatement 对象
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1,"大美女");
preparedStatement.setInt(2,3);
//执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}
}
JDBC中事务
1、JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个 SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
2、JDBC程序中为了让多个 SQL语句作为一个整体执行,需要使用事务
3、调用 Connection 的 setAutoCommit(false)可以取消自动提交事务
4、在所有的 SQL语句都成功执行后,调用 Connection 的commit();方法提交事务
5、在其中某个操作失败或出现异常时,调用 rollback0);方法回滚事务