上个随笔记录了各数据库连接字符串的写法,这里补充数据库连接步骤。
1.0 加载驱动
使用Class.forname("drivername")方法加载相应的数据库驱动
drivername : 数据库驱动类名
Sql Server: com.microsoft.jdbc.sqlserver.SQLServerDriver
Oracle: oracle.jdbc.driver.OracleDriver
MySql: com.mysql.jdbc.Driver
Class.forname()的作用是把指定的类或驱动加载到jvm中,供application使用。
1.1 获得数据库连接对象Connection
1.0加载成功后对应数据实例注册到DriverManager类中
然后我们通过DriverManager.getConnection("url","username","pwd"); 得到连接对象
url:数据库连接字符串
username:数据库用户名
pwd:数据库密码
通过上述步骤数据的连接工作已经做好了接下来就是对数据库的操作了
1.2 创建Statement对象操作数据库
ps:强烈建议是PreparedStatement对象来操作数据,因为PreparedStatement运行sql参数以"?"为占位符的方式对sql进行预编译这样防止了sql注入
sql注入:
String Sql=select * from user where username="" and password=""
由于没有对拼接的字符进行检查,很容易遭受到恶意的攻击,例如变成如下操作。
select * from user where username='老李' or '1'='1' and password=";
由此产生了SQL注入的问题。
Statement对象提供了许多对数据库增删改查的方法(下面情看代码示例)
代码示例:
package com.pf.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCTest { private Connection con; public JDBCTest() throws ClassNotFoundException, SQLException{ //1. load JDBC驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@127.0.0.1:1521:test"; String username= "scott"; String pwd = "tiger"; //2. 获取连接对象 con = DriverManager.getConnection(url,username,pwd); } //添加 public boolean add() throws SQLException{ String sql = "insert into a values(?,?)"; //Statement statement = con.createStatement(); PreparedStatement statement = con.prepareStatement(sql); //给占位符赋值 statement.setInt(1, 102); statement.setString(2, "JDBCTest"); int execute = statement.executeUpdate(); System.out.println("执行结果:"+ execute); return execute>0; } // 删除 public boolean delete() throws SQLException{ String sql = "delete a where id=?"; //Statement statement = con.createStatement(); PreparedStatement statement = con.prepareStatement(sql); statement.setInt(1, 101); int execute = statement.executeUpdate(); System.out.println("执行结果:"+ execute); return execute>0; } //修改 public boolean update() throws SQLException{ String sql = "update a set name=? where id=?"; //Statement statement = con.createStatement(); PreparedStatement statement = con.prepareStatement(sql); statement.setString(1, "修改100"); statement.setInt(2, 100); int execute = statement.executeUpdate(); System.out.println("执行结果:"+ execute); return execute>0; } // 查询 public void search() throws SQLException{ String sql = "select * from a"; //Statement statement = con.createStatement(); PreparedStatement statement = con.prepareStatement(sql); ResultSet set = statement.executeQuery(); while( set.next()){ System.out.println("ID:"+set.getString("id")+" Name:"+set.getString("name")); System.out.println(); } } public static void main(String[] args) throws ClassNotFoundException, SQLException { JDBCTest test = new JDBCTest(); //test.add(); //test.delete(); //test.update(); test.search(); } }