一:JDBC概述:
JDBC是与数据库获取连接的API,用来执行sql语句。
二:JDBC的使用步骤:
1.注册驱动
2.获取连接;
3.获取操作对象;
4.编写并执行SQL语句;
5.处理查询结果;
6.释放资源;
三:具体操作:
1.注册驱动(Driver):
import java.sql.SQLException;
import com.mysql.cj.jdbc.Driver;
public class test2 {
public static void main(String [] args) throws Exception
{
//注册驱动的方法
//1.
Driver driver=new Driver();
//2.
Class.forName("com.mysql.cj.jdbc.Driver");
}
}
第二种方法是通过反射类创建的,其中"com.mysql.cj.jdbc.Driver"是固定格式。
2.获取连接(DriverManager):![](https://img-blog.csdnimg.cn/direct/c6cea38cfc3c40259bedd90c0444bc4f.jpeg)
Connection connection=DriverManager.getConnection
("jdbc:mysql://localhost:3306/wxy?serverTimezone=GMT%2B8","root","13579");
获取连接的唯一方法,DriverManager.getConnection(url,username,password)方法有三个参数,
url:连接数据库的地址;格式:"jdbc:mysql://主机名(hostname):端口号(默认为3306)/mysql中对应的数据库名称"-----"jdbc:mysql://localhost:3306/wxy";
username:登录数据库的用户名;
password:登录数据库的密码;
3.获取操作对象(Connection):![](https://img-blog.csdnimg.cn/direct/14ae72e764d0493f939564f5f16fe766.jpeg)
两种方法获取操作对象,第一个返回一个Statement类型的对象可以没有参数,第二个返回一个preparedStatement类型的对象且参数为sql语句。
java.sql.Statement statement=connection.createStatement();
PreparedStatement preparedStatement=connection.prepareStatement("sqlstring");
4.编写并执行sql语句:
(1) Statement:![](https://img-blog.csdnimg.cn/direct/929c6903962a453a98610c9f9f24493d.jpeg)
Statement提供了三种执行sql语句的方法; executeQuery()返回一个表示查询结果的ResultSet类型的对象;executeUpdate()返回数据库中受该sql语句影响的记录条数。
String sqlString="select realname from user";
ResultSet resultSet=statement.executeQuery(sqlString);
(2) PreparedStatement:(防注入) PreparedStatement是Statement的子接口,该接口的sql语句可以用"?"占位符代替参数,然后用setter()方法为sql语句赋值。"?"从1开始,依次递加,直至最后一个"?"。
String sqlString="insert into user values (?,?,?)";
statement=connection.prepareStatement(sqlString);
statement.setInt(1,user.getId());
statement.setString(2,user.getNameString());
statement.setString(3,user.getPasswordString());
int n=statement.executeUpdate();
System.out.println(n);