什么是JDBC?
JDBC是一种可以执行sql语句的Java API,提供对数据库的访问方法。
什么是JDBC驱动?
JDBC连接数据库需要驱动,驱动是两个设备要进行通信,满足一定的数据驱动格式。一般驱动都是由数据库厂家提供的。
JDBC原理:
Java提供访问数据库规范称为JDBC,而生产厂商提供规范的实现类称为驱动。
JDBC是接口,驱动是接口的实现,没有驱动将无法完成数据库连接,从而不能操作数据库!
JDBC的开发步骤:
- 注册驱动.
- 获得连接.
- 获得语句执行平台
- 执行sql语句
- 处理结果
- 释放资源.
导入驱动包:
创建lib目录,用于存放当前项目需要的所有jar包
选择jar包,右键执行build path / Add to Build Path
JDBC工具类代码:
/*
* JDBC工具类
*/
public class JDBCUtils {
public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/mydb";
public static final String USER = "root";
public static final String PASSWORD = "root"; static {
try {
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
System.out.println("数据库驱动注册失败!");
}
}
//提供获取连接的方法
public static Connection getConn() throws Exception {
// 2. 获得连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
// 返回连接
return conn;
}
}
使用properties文件获取配置文件:
开发中获得连接的4个参数(驱动、URL、用户名、密码)通常都存在配置文件中,方便后期维护,程序如果需要更换数据库,只需要修改配置文件即可。
通常情况下,我们习惯使用properties文件,此文件我们将做如下要求:
- 文件位置:任意,建议src下
- 文件名称:任意,扩展名为properties
- 文件内容:一行一组数据,格式是“key=value”.
a) key命名自定义,如果是多个单词,习惯使用点分隔。例如:jdbc.driver
b) value值不支持中文,如果需要使用非英文字符,将进行unicode转换。
创建文件:
在项目跟目录下,创建文件,输入“db.properties”文件名。
l 文件中的内容
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
user=root
password=root
加载配置文件 properties 对象:
对应properties文件处理,开发中也使用Properties对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。
l JDBCUtils.java中编写代码
public class JDBCUtils { private static String driver;
private static String url;
private static String user;
private static String password;
// 静态代码块
static {
try {
// 1 使用Properties处理流
// 使用load()方法加载指定的流
Properties props = new Properties();
Reader is = new FileReader("db.properties");
props.load(is);
// 2 使用getProperty(key),通过key获得需要的值,
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
} catch (Exception e) {
throw new RuntimeException(e);
}
} /**
* 获得连接
*/
public static Connection getConnection() {
try {
// 1 注册驱动
Class.forName(driver);
// 2 获得连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
使用工具类:
public class Demo {
@Test
public void insert(){
try{
//1,获取连接对象
Connection conn = JDBCUtils.getConnection();
//2,指定要执行的SQL语句
String sql = "INSERT INTO zhangwu(name,money,parent) VALUES(?,?,?)";
//4,获取SQL语句的执行对象 PreparedStatement
PreparedStatement ppstat = conn.prepareStatement(sql);
//5,执行SQL语句
ppstat.setString(1, "股票收入");
ppstat.setDouble(2, 5000);
ppstat.setString(3, "收入");
int line = ppstat.executeUpdate();
//6,处理结果集
System.out.println("line=" + line);
//7,关闭连接
ppstat.close();
conn.close();
} catch(SQLException e){
throw new RuntimeException(e);
}
}
}