数据库编程的必备条件:
JDBC,即Java Database Connectivity,java数据库连接。是一种用于执行SQL语句的Java API,它是Java中的数据库连接规范。这个API由 java.sql.* ,javax.sql.* 包中的一些类和接口组成,它为Java开发人员操作数据库提供了一个标准的API,可以为多种关系数据库提供统一访问。
JDBC工作原理:
JDBC 为多种关系数据库提供了统一访问方式,作为特定厂商数据库访问API的一种高级抽象,它主要包含一些通用的接口类。
JDBC访问数据库层次结构:
JDBC API: 在Java JDBC编程中对数据库的操作均使用JDK自带的API统一处理,通常与特定数据库的驱动类是完全解耦的。所以掌握Java JDBC API (位于 java.sql 包下) 即可掌握Java数据库编程。
JDBC优势:
前期工作分为以下几部分:
//方法1:一种是通过DriverManager(驱动管理类)的静态方法获取:
// 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test?
user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
//MySQL数据连接的URL参数格式如下:jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
//方法2:一种是通过DataSource(数据源)对象获取。实际应用中会使用DataSource对象。
DataSource ds = new MysqlDataSource();
((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/test");
((MysqlDataSource) ds).setUser("root");
((MysqlDataSource) ds).setPassword("root");
Connection connection = ds.getConnection();
以上两种方式的区别是:
(1) DriverManager类来获取的Connection连接,是无法重复利用的,每次使用完以后释放资源时,通过connection.close()都是关闭物理连接。
(2) DataSource提供连接池的支持。连接池在初始化时将创建一定数量的数据库连接,这些连接是可以复用的,每次使用完数据库连接,释放资源调用connection.close()都是将Conncetion连接对象回收。
Statement statement = connection.createStatement();
实际开发中最常用的是PreparedStatement对象,以下对其的总结:
ResultSet resultSet= statement.executeQuery(
"select id, sn, name, qq_mail, classes_id from student");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String sn = resultSet.getString("sn");
String name = resultSet.getString("name");
int classesId = resultSet.getInt("classes_id");
System.out.println(String.format("Student: id=%d, sn=%s, name=%s,
classesId=%s", id, sn, name, classesId));
}
//关闭结果集
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭命令
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭连接命令
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
通过下面代码分别实现了在IDEA中对数据库的增删改查操作:
TestDemo.java:
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.*;
public class TestDemo {
//查询示例
/*public static void main1(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
Connection connection =
DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String sql = "select * from user";
Statement statement = connection.createStatement();
//结果集
ResultSet resultSet = statement.executeQuery(sql);//查询
if(resultSet.next()){
System.out.println(resultSet.getInt(1));//查询的数据库的这个表的第一列
System.out.println(resultSet.getString(2));//查询的数据库的这个表的第二列
System.out.println(resultSet.getString(3));
}
}*/
/* public static void main2(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
Connection connection =
DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String sql = "select * from user";
Statement statement = connection.createStatement();
//结果集
ResultSet resultSet = statement.executeQuery(sql);//查询
User user = new User();
if(resultSet.next()){
user.setId(resultSet.getInt(1));//查询的数据库的这个表的第一列
user.setName(resultSet.getString(2));//查询的数据库的这个表的第二列
user.setPassword(resultSet.getString(3));
}
System.out.println("查询到的数据是"+user);
}*/
/*public static void main3(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
Connection connection =
DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String sql = "select * from user where name = 'feihan' and password = '123'";
Statement statement = connection.createStatement();
//结果集
ResultSet resultSet = statement.executeQuery(sql);//查询
User user = new User();
if(resultSet.next()){
user.setId(resultSet.getInt(1));//查询的数据库的这个表的第一列
user.setName(resultSet.getString(2));//查询的数据库的这个表的第二列
user.setPassword(resultSet.getString(3));
}
System.out.println("查询到的数据是"+user);
}*/
/*public static void main4(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
Connection connection =
DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String uname = "feihan";
String upass = "123";
// String upass = " 1' or '1' = '1 ";//sql注入
String sql = "select * from user where name = '"+uname+"' and password = '"+upass+"'";
Statement statement = connection.createStatement();
//结果集
ResultSet resultSet = statement.executeQuery(sql);//查询
User user = new User();
if(resultSet.next()){
user.setId(resultSet.getInt(1));//查询的数据库的这个表的第一列
user.setName(resultSet.getString(2));//查询的数据库的这个表的第二列
user.setPassword(resultSet.getString(3));
}
System.out.println("查询到的数据是"+user);
}*/
/*public static void main5(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
//Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
DataSource dataSource = new MysqlDataSource();//获取数据源
((MysqlDataSource)dataSource).setUrl(url);
((MysqlDataSource)dataSource).setUser(username);
((MysqlDataSource)dataSource).setPassword(password);
Connection connection = dataSource.getConnection();
//MysqlDataSource mysqlDataSource = new MysqlDataSource();
//Connection connection =DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String uname = "feihan";
String upass = "123";
//String upass = " 1' or '1' = '1 ";//sql注入
//SQL注入:出现在当你的SQL语句是字符串拼接的情况下。
//String sql = "select * from user where name = '"+uname+"' and password = '"+upass+"'";
String sql = "select * from user where name = ? and password = ?";
//PreparedStatement预防了sql注入,因为它在看到''这种符号的时候加了一个斜杠进行注释
//Statement statement = connection.createStatement();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,uname);
preparedStatement.setString(2,upass);
System.out.println("sql:"+preparedStatement.toString());
//结果集
ResultSet resultSet = preparedStatement.executeQuery();//查询
User user = new User();
if(resultSet.next()){
user.setId(resultSet.getInt(1));//查询的数据库的这个表的第一列
user.setName(resultSet.getString(2));//查询的数据库的这个表的第二列
user.setPassword(resultSet.getString(3));
}
System.out.println("查询到的数据是"+user);
resultSet.close();
preparedStatement.close();
connection.close();
}*/
//插入示例:
/*public static void main6(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
//Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
DataSource dataSource = new MysqlDataSource();//获取数据源
((MysqlDataSource)dataSource).setUrl(url);
((MysqlDataSource)dataSource).setUser(username);
((MysqlDataSource)dataSource).setPassword(password);
Connection connection = dataSource.getConnection();
//MysqlDataSource mysqlDataSource = new MysqlDataSource();
//Connection connection =DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String uname = "feihan1";
String upass = "1234";
//String upass = " 1' or '1' = '1 ";//sql注入
//String sql = "select * from user where name = '"+uname+"' and password = '"+upass+"'";
String sql = "insert into uesr (id,name,password) values(?,?,?)";//?是占位符
//更新多条的话String sql = "insert into uesr (id,name,password) values(?,?,?),(?,?,?)...";
//PreparedStatement预防了sql注入,因为它在看到''这种符号的时候加了一个斜杠进行注释
//Statement statement = connection.createStatement();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);
preparedStatement.setString(2,uname);
preparedStatement.setString(3,upass);
System.out.println("sql:"+preparedStatement.toString());
//结果集
int ret = preparedStatement.executeUpdate();//查询
if(ret != 0){
System.out.println("插入成功!");
}
preparedStatement.close();
connection.close();
}*/
//修改示例:
/* public static void main7(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
//Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
DataSource dataSource = new MysqlDataSource();//获取数据源
((MysqlDataSource)dataSource).setUrl(url);
((MysqlDataSource)dataSource).setUser(username);
((MysqlDataSource)dataSource).setPassword(password);
Connection connection = dataSource.getConnection();
//MysqlDataSource mysqlDataSource = new MysqlDataSource();
//Connection connection =DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String uname = "feihan2";
String upass = "1234";
//String upass = " 1' or '1' = '1 ";//sql注入
//String sql = "select * from user where name = '"+uname+"' and password = '"+upass+"'";
String sql = "update uesr set name = ? where id = ?";//?是占位符
//更新多条的话String sql = "insert into uesr (id,name,password) values(?,?,?),(?,?,?)...";
//PreparedStatement预防了sql注入,因为它在看到''这种符号的时候加了一个斜杠进行注释
//Statement statement = connection.createStatement();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//preparedStatement.setInt(1,2);
preparedStatement.setString(1,uname);
preparedStatement.setInt(2,2);
System.out.println("sql:"+preparedStatement.toString());
//结果集
int ret = preparedStatement.executeUpdate();//查询
if(ret != 0){
System.out.println("更新成功!");
}
preparedStatement.close();
connection.close();
}*/
//删除示例:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1.加载驱动:
//Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:
String url = "jdbc:mysql://127.0.0.1:3306/数据库名字";
//或 String url = "jdbc:mysql://localhost:3306/数据库名字";
String username = "root";//数据库名称
String password = "123456";//数据库的密码
DataSource dataSource = new MysqlDataSource();//获取数据源
((MysqlDataSource)dataSource).setUrl(url);
((MysqlDataSource)dataSource).setUser(username);
((MysqlDataSource)dataSource).setPassword(password);
Connection connection = dataSource.getConnection();
//MysqlDataSource mysqlDataSource = new MysqlDataSource();
//Connection connection =DriverManager.getConnection(url, username,password);
//3.执行SQL语句
String sql = "delete from user where id = ?";//?是占位符
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);
System.out.println("sql:"+preparedStatement.toString());
//结果集
int ret = preparedStatement.executeUpdate();//查询
if(ret != 0){
System.out.println("删除成功!");
}
preparedStatement.close();
connection.close();
}
}
User.java:
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}