一、jdbc:
JDBC:java database connectivity:sun公司为了简化和统一java连接数据库,定义的一套规范(API,接口).
jdbc和数据库驱动的关系: 接口(JDBC)与实现(驱动jar包)的关系
二、使用JDBC连接mysql数据库步骤
1. 注册驱动:Class.forName(“com.mysql.jdbc.Driver”);
2. 获得连接:
- Connection connection = DriverManager.getConnection(url, username, password);
- url:“协议:子协议://ip地址:端口号/数据库名” -->“jdbc:mysql://localhost:3306/test”
- username:mysql用户名
- password:mysql密码
3. 获取sql语句执行对象:
statement对象:
Statement sta = connection.createStatement();
- 主要方法:
ps.executeUpdate(sql语句);//根据执行的DML(insert update delete)语句,返回受影响的行数。
ps.executeQuery(sql语句);//根据查询语句返回结果集。只能执行select语句。
ps.execute();//此方法可以执行任意sql语句。true: 代表执行select, 并且有结果 false: 执行insert,delete,update
preparedStatement对象:
PreparedStatement ps = connection.prepareStatement(sql语句);//使用占位符替代要传入的值
- 主要方法:
通过setxxx方法来指定参数(替换占位符)
prepareStatement.setxxx(int i, Object value);// i 指的就是问号的索引(指第几个问号,从1开始),xxx是类型(eg:int,String,Long)
- 注意: 使用PreparedStatement可以防止sql注入。
4.释放资源:
- 如果有resultSet, statement,connection这些对象,调依次调用其close()方法。
4.SQL注入:
- 把用户输入的内容注入到了sql语句里面去了(其中一种:本来你的sql语句中的where是判断用户名和密码的,结果用户输入的内容把你判断密码的这个判断条件给注释了)。
5.创建JdbcUtis工具类时:
- driver、url、user、password(建议是私有的、静态的成员变量) //静态代码快中
- 读取jdbc.properties中的值,并赋值本类类名.class.getClassLoader().getResourceAsStream(“jdbc.properties”);//类加载已经达到了src里面了 其中jdbc.properties在src目录下。
- Calss.forName(driver);
- 获取连接的方法
- 释放资源的方法
JdbcUtils.class(记得导入mysql驱动包)
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String url;
private static String username;
private static String password;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception{
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(ResultSet resultSet, Statement statement,Connection connection){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException();
}finally {
if (statement!=null){}
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException();
}finally {
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException();
}
}
}
}
}
}
}
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名
username=root
password=mysql密码