1.加载驱动(以oracle为例子)
Class.forName("oracle.jdbc.driver.OracleDriver");
2.通过DriverManager连接数据库(返回值为一个Connection对象)
DriverManager.getConnection(url, UserName, password);
3.Statement方法不介绍了,只介绍PerparedStatement,因为效率高,并且防止SQL的注入
PreparedStatement preparedStatement = connection.prepareStatement(sql);
在这里,PreparedStatement的sql语句可以使用占位符?来替代
例如:
PreparedStatement preparedStatement = connection.prepareStatement("insert into Persons values(null,?)");
4.添加数据
//preparedStatement.setString(parameterIndex, x);
preparedStatement.setString(1, “数据”);
5.提交数据
preparedStatement.executeUpdata();
//这里不需要添加参数,因为他已经储存了预编译的SQL语句
6.获取返回值
7.释放资源
tips:对于数据的增删改查,都推荐改成手动提交,若提交失败,可数据回流
例子:
package com.mysqltest.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SqlTest {
public static void main(String[] args) throws SQLException {
//封装成工具类加载驱动
Connection connection = JDBCUtil.getConnection();
//设置为手动提交
connection.setAutoCommit(false);
//创建sql语句
String sql = "insert into Persons values(?,?,?,?,?)";
//创建对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//传入数据
preparedStatement.setString(0, "hello");
preparedStatement.setInt(1, 18);
preparedStatement.setString(2, "hello");
preparedStatement.setString(3, "hello");
preparedStatement.setString(4, "hello");
try {
//提交数据
int i = preparedStatement.executeUpdate();
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
//数据回滚
connection.rollback();
e.printStackTrace();
} finally {
//关闭资源
connection.close();
preparedStatement.close();
}
}
}
最开始的加载驱动使用了一个工具类
如下:
package com.mysqltest.test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtil {
private static String driver;
private static String url;
private static String usernmae;
private static String password;
static {
String dbproperties = "/db.properties";
//获取属性文件的内容
Properties properties = new Properties();
//获取属性文件的流对象
InputStream inputStream = JDBCUtil.class.getResourceAsStream(dbproperties);
try {
//加载属性文件
properties.load(inputStream);
//获取参数
driver = properties.getProperty("driver");
url = properties.getProperty("url");
usernmae = properties.getProperty("usename");
password = properties.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, usernmae, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
重点提示:JDBCUtil.class.getResourceAsStream()这个路径就是src!!!