一、加载驱动连接数据库
//加载驱动器
try {
Class.forName("oracle.jdbc.OracleDriver");
System.err.println("注册成功...");
} catch (ClassNotFoundException e) {
System.err.println("注册异常");
}
String url = "jdbc:oracle:thin:@127.0.0.1:1521/xe";
//连接数据库
try {
con = DriverManager.getConnection(url,"jingxi","1234");
System.err.println("连接成功...");
System.err.println(con);
}
con.close();
System.err.println("连接关闭...");
} catch (SQLException e) {
System.err.println("连接异常");
}
}
二、增删改查createStatement
Connection con;
Statement st;
ResultSet rs;
1.查询数据
st = con.createStatement();
rs = st.executeQuery("select * from jingxi_user");
while (rs.next()) {
String id= rs.getString(1);
String name = rs.getString(2);
String psd = rs.getString(3);
System.err.println(id+"|"+ name +"|"+ psd);
}
System.err.println("----------");
rs.close();
st.close();
2.插入数据
Scanner sc = new Scanner(System.in);
System.err.println("plz enter your name:");
String name = sc.nextLine();
System.err.println("plz enter your psd:");
String psd = sc.nextLine();
String sql = "insert into jingxi_user values('" +id+ "','"+name+"','"+psd+"')";
int i = st.executeUpdate(sql);
System.err.println("影响" + i + "行数据");
st.close();
con.close();
3.删除数据
Scanner sc = new Scanner(System.in);
System.err.println("plz enter id:");
String id = sc.nextLine();
String sql = "delete jingxi_user WHERE id ='"+id+"'";
int i = st.executeUpdate(sql);
System.err.println("删除" + i + "行数据");
st.close();
4.更改数据
Scanner sc = new Scanner(System.in);
System.err.println("plz enter your id:");
String id = sc.nextLine();
System.err.println("plz enter your name:");
String name = sc.nextLine();
String sql = "update JINGXI_USER set NAME='"+name+"'where ID='"+id+"'";
int i = st.executeUpdate(sql);
System.err.println("更改" + i + "行数据");
st.close();
三、批处理SQL语句
String sql = "insert into users values( ? , ?)";
pst = con.prepareStatement(sql);
// String id = UUID.randomUUID().toString().replaceAll("-", "");
// System.err.println(UUID.randomUUID().toString());
Scanner sc = new Scanner(System.in);
System.err.println("plz enter your name:");
String name = sc.nextLine();
System.err.println("plz enter your psd:");
String psd = sc.nextLine();
for (int i = 1; i <=10; i++) {
pst.setString(1, name + i);
pst.setString(2, psd + i);
pst.addBatch();
}
int[] s = pst.executeBatch();
System.err.println("影响" + s.length + "行数据");
pst.close();
con.close();
void | addBatch() 向这个 PreparedStatement对象的一批命令添加一组参数。 |
int[] s = pst.executeBatch();提交执行所有语句
四、调用存储过程CallableStatement
public void callAble() throws Exception{
Scanner sc = new Scanner(System.in);
Connection con = ConnUtils.getCon();
String sql = "{call pl(?,?)}";
CallableStatement cst = con.prepareCall(sql);
System.err.println("plz enter user");
String name = sc.nextLine();
System.err.println("plz enter psd");
String psd = sc.nextLine();
cst.setString(1, name);
cst.setString(2, psd);
int i = cst.executeUpdate();
System.err.println("影响数据行数"+i);
cst.close();
con.close();
}
使用CallableStatement cst = con.prepareCall(sql);
五、使用Connection控制事务保证数据一致性
con.setAutoCommit(false);
con.setAutoCommit(true);
con.commit();
con.rollback();
1.如果不开事务某句sql语句出错会导致数据不一致此时应该操作事务
@Test
public void transaction() throws Exception{
Connection con = ConnUtils.getCon();
st = con.createStatement();
st.execute("update users set password = password+3 where name = 'er1'");
st.execute("update users set password = password-3 where name = 'er2");
st.close();
con.close();
}
2.使用connection关闭自动提交事务 以保证异常之后数据可以回滚
@Test
public void transaction() throws Exception{
Connection con = ConnUtils.getCon();
st = con.createStatement();
try {
con.setAutoCommit(false);
st.execute("update users set password = password+3 where name = 'er1'");
st.execute("update users set password = password-3 where name = 'er2"); con.commit();
}catch(Exception e){
con.rollback();
} finally {
con.setAutoCommit(true);
}
st.close();
con.close();
}
六、元数据分析
主要类DatabaseMetaData
ResultSetMetaData
1. 数据库元数据分析
获取数据库名称及版本
// 获取数据库元数据
@Test
public void dataMate() throws Exception {
con = ConnUtils.getCon();
DatabaseMetaData dm = con.getMetaData();
// output
System.err.println("数据库的名称:" + dm.getDatabaseProductName());
System.err.println("数据库的版本:" + dm.getDatabaseMajorVersion() + "." + dm.getDatabaseMinorVersion());
con.close();
}
获取数据库中的所有表
// 获取数据库有哪些表
@Test
public void dataMateTb() throws Exception {
con = ConnUtils.getCon();
DatabaseMetaData dm = con.getMetaData();
// 获取有多少表
rs = dm.getTables("JINGXI", "JINGXI", null, new String[] { "TABLE" });
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
System.err.println(name);
}
con.close();
}
2. 结果集元数据分析
//结果集元数据分析
@Test
public void resultMate() throws Exception{
con = ConnUtils.getCon();
String sql = "select * from jingxi_user";
st = con.createStatement();
rs = st.executeQuery(sql);
ResultSetMetaData rsm = rs.getMetaData();
int col = rsm.getColumnCount();
for(int i = 1 ; i <= col ; i++) {
String name = rsm.getColumnName(i);
String type = rsm.getColumnTypeName(i);
int size = rsm.getColumnDisplaySize(i);
System.err.print(name+" "+type+ " "+"("+size+")"+"\t");
}
System.err.println();
while(rs.next()) {
for(int i = 1 ; i <= col ; i++) {
String values = rs.getString(i);
System.err.print(values+"\t\t");
}
System.err.println();
}
}
七、封装con
单例模式、工厂模式
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnUtils {
第一步:private static Connection con;
第二步:static { ///}
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
System.err.println("注册异常");
}
String url = "jdbc:oracle:thin:@localhost:1521/xe";
String user = "jingxi";
String psd = "1234";
try {
con = DriverManager.getConnection(url, user, psd);
} catch (SQLException e) {
System.err.println("连接异常");
}
}
第三步:public static Connection getCon() {
return con;
}
}
八、读取资源文件连接数据库
第一步:创建资源文件*.properties放在bin目录下并改编码为GBK;
第二步:配置资源文件
#配置oracle连接
driver = oracle.jdbc.OracleDriver
url = jdbc:oracle:thin:@localhost:1521/xe
name = jingxi
psd = 1234
#配置mysql连接
#driver = com.mysql.jdbc.Driver
#url = jdbc:mysql://localhost:3306/db_database07?characterEncoding=UTF-8
#name = root
#psd = psd
第三步:读取资源文件
Properties pro = new Properties();
pro.load(ClassLoader.getSystemResourceAsStream("jdbc.properties"));
String driver = pro.getProperty("driver");
String url = pro.getProperty("url");
String name = pro.getProperty("name");
String psd = pro.getProperty("psd");
第四步:连接数据库
Class.forName(driver);
con = DriverManager.getConnection(url, name, psd);
附件
1. SQL注入与解决方法
什么是SQL注入
st = con.createStatement();
System.err.println("plz enter user");
String name = sc.nextLine();
System.err.println("plz enter psd");
String psd = sc.nextLine();
rs = st.executeQuery("select * from users where name = '"+name+"' and password = '"+psd+"'");
if (rs.next()) {
System.err.println("load..");
}else {
System.err.println("error");
}
拼接字符串通过关键字方式 使条件成立的漏洞为SQL注入漏洞;
解决方案
使用PreparedStatement进行sql预编译
ResultSet | 执行此 PreparedStatement对象中的SQL查询,并返回查询 PreparedStatement的 ResultSet对象。 |
int | 执行在该SQL语句PreparedStatement对象,它必须是一个SQL数据操纵语言(DML)语句,如INSERT , UPDATE或DELETE ; 或不返回任何内容的SQL语句,例如DDL语句。 |
代码展示:
//st = con.createStatement();
pst = con.prepareStatement("select * from users where name = ? and password = ?");
System.err.println("plz enter user");
String name = sc.nextLine();
System.err.println("plz enter psd");
String psd = sc.nextLine();
pst.setString(1, name);
pst.setString(2, psd);
rs = pst.executeQuery();
//rs = st.executeQuery("select * from users where name = '"+name+"' and password = '"+psd+"'");
if (rs.next()) {
System.err.println("load..");
}else {
System.err.println("error");
}
rs.close();
//st.close();
pst.close();
此时不会再出现异常问题以及注入问题