JDBC connection database operation
1. Several elements of JDBC database connection
- The standard of JDBC URL consists of three parts, each part is separated by a colon
Format:
jdbc:<子协议>:<子名称>
- Protocol: The protocol in the JDBC URL is always jdbc
- Subprotocol: The subprotocol is used to identify a database driver
- Subname: A way to identify a database. The sub-name can be changed according to different sub-protocols, the purpose of using the sub-name is to provide enough information for locating the database
- JDBC URLs for several commonly used databases:
- Oracle database:
- jdbc:oracle:thin:@localhost:1521:orcl (database name, generally default to orcl)
- SQL Server database:
- jdbc:Microsoft:sqlserver//localhost:1433:DatabaseName=sid(database name)
- MySQL database:
- jdbc:mysql://localhost://3306/sid(database name)
- : 1521, 1433, 3306 represent the listening port number of the database
- Oracle database:
2. Use the basic Driver to connect to the database
Single connection fixed database:
public void tes1t() { try { //1.创建Driver实现类的对象 Driver driver = new com.mysql.jdbc.Driver(); System.out.println(driver); //2.创建连接数据库的内容(用户名、密码)对象 Properties properties = new Properties(); //3.设置数据库地址 String url = "jdbc:mysql://127.0.0.1:3306/company"; //3.向对象中 插入数据库登陆的用户名与密码 properties.put("user", "root"); properties.put("password", "java123"); //4.通过驱动获取数据库连接对象 Connection coon = driver.connect(url, properties); System.out.println(coon); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
The running result is shown in the figure:
Dynamically obtain database drivers through reflection mechanism
Configuration file: my.properties
driverClass=com.mysql.jdbc.Driver jdbcUrl=jdbc:mysql://localhost:3306/java user=root password=java123 //注意:在properties文件中,注释是以#号开头的,在这里使用了// //driverClass=oracle.jdbc.driver.OracleDriver //jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl //user=scott //password=java123
Test Case:
public void test3() throws Exception{ String driverName; String jdbcUrl; String user; String password; //1.获取当前类对象下的文件 InputStream is = getClass().getClassLoader().getResourceAsStream("my.properties"); Properties ps = new Properties(); ps.load(is); //3.获取响应的文件内容 driverName = ps.getProperty("driverClass"); jdbcUrl = ps.getProperty("jdbcUrl"); user = ps.getProperty("user"); password = ps.getProperty("password"); //调用方法返回连接数据库对象 Connection coo = getConnection(driverName, jdbcUrl, user, password); System.out.println(coo); } //获取数据库连接方法 public Connection getConnection(String driverName, String driverPath, String name, String pwd){ Connection connection = null; try { //1.通过反射机制获取Driver实现类的对象 @SuppressWarnings("static-access") Driver driver = (Driver)getClass().forName(driverName).newInstance(); Properties info = new Properties(); info.put("user", name); info.put("password", pwd); //2.获取数据库连接对象 connection = driver.connect(driverPath, info); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; }
The results of connecting the two databases are shown in the following figures: just change the configuration file (.properties)
Connect to MySQL database
Connect to Oracle database
3. JDBC connects to the database and implements database operations through PreparedStatement (Statement) objects
- Using PreparedStatement can effectively avoid injection problems caused by string concatenation in database operations
- Using PreparedStatement can effectively optimize the code
The following is a case of connecting to the MySQL database and operating the database, using the object-oriented (Java Bean) form to operate the database, such as:
Java Bean:customer.class
package com.ajb.statement; /** * Java Bean 对象 * @author duanjunhua * */ public class Customer { private String name; private String password; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
主类:TestPreparedStatement.class
package com.ajb.statement; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.Scanner; import org.junit.Test; public class TestPreparedStatement { Connection coon = null; PreparedStatement pStatement = null; private boolean flag; private Customer customer; private String sql; private int Id; @Test public void test(){ //1.获取Java Bean对象 customer = getCustomer(); //2.创建SQL语句 if(customer == null) return; else{ //PreparedStatement使用占位符的形式 if(customer.getId()==1){ sql = "insert into customer values(?, ?)"; }else if(customer.getId() == 2){ sql = "select * from customer where name=? and password=?"; } } //3.获取数据库连接对象 coon = getConnection(); //表若不存在则创建表 if(tableExists(coon) == false){ createTable(coon); } //4.执行SQL语句操作 executeSQL(coon, sql, customer); //5.释放连接(必须手动释放) release(coon, pStatement); } //判断数据库表是否存在 public boolean tableExists(Connection connection){ flag = false; String sqlquery = "select table_name from information_schema.tables"; try { pStatement = connection.prepareStatement(sqlquery); ResultSet resultSet = pStatement.executeQuery(); while (resultSet.next()) { if(resultSet.getString(1).equals("customer")){ flag = true; return flag; } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } //创建表 public void createTable(Connection connection){ String sql = "create table customer(" + "name varchar(15)," + "password varchar(15)" + ")"; try { //获取PreparedStatement对象 pStatement = connection.prepareStatement(sql); pStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //从键盘输入获取Java Bean对象数据 public Customer getCustomer(){ Customer customer = new Customer(); Scanner scanner = new Scanner(System.in); System.out.println("请选择模式:1、注册用户\n\t 2.用户登录"); customer.setId(scanner.nextInt()); //如果是两者之外的其他模式,直接退出并提示用户信息 if(customer.getId()!= 1 && customer.getId() != 2){ System.out.println("选择错误,请重新运行输入..."); return null; } System.out.print("请输入用户名:"); customer.setName(scanner.next()); System.out.print("请输入登录密码:"); customer.setPassword(scanner.next()); return customer; } //获取数据库的配置文件 //根据配置文件获取对应的数据库连接对象 public Connection getConnection(){ // Properties ps = new Properties(); try { InputStream is = getClass().getClassLoader().getResourceAsStream("my.properties"); ps.load(is); coon = DriverManager.getConnection(ps.getProperty("jdbcUrl"), ps.getProperty("user"), ps.getProperty("password")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return coon; } //执行数据库的更新操作 public void executeSQL(Connection connection, String sql, Customer customer){ try { //4.由连接对象获取PreparedStatement对象 pStatement = connection.prepareStatement(sql); //5.加载数据 if(customer.getId() == 1){ if(TestPreparedStatement.queryUser(connection,customer) == false){ TestPreparedStatement.update(pStatement, customer.getName(), customer.getPassword()); pStatement.executeUpdate(); }else { System.out.println("用户名已存在,请重新输入用户名!!!"); return; } }else { TestPreparedStatement.update(pStatement, customer.getName(), customer.getPassword()); ResultSet resultSet = pStatement.executeQuery(); while(resultSet.next()){ System.out.println("登录成功 !!!"); return; } System.out.println("用户名或密码错误,请重新登录!!!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //使用setXxx()方法填充占位符 public static void update(PreparedStatement pStatement, Object ... objects) throws SQLException{ for(int i = 0; i < objects.length; i++){ pStatement.setObject(i + 1, objects[i]); } } //6.关闭数据库连接 public static void release(Connection connection, PreparedStatement pStatement){ if(pStatement != null){ try { pStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //查询用户名是否存在 public static boolean queryUser(Connection connection,Customer customer){ //Statement使用字符串拼接的形式 String sql = "select name from customer where name= '" + customer.getName() + "'"; try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { return true; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
Create the database at the same time when registering for the first time
registration failed
login successful
Login failed
database
Note: The corresponding database driver is required when connecting to the database, as shown in the figure:
Project directory
- Create a new lib folder in the project directory, and copy the corresponding driver .jar file to this directory
- Right-click Build Path -> Add to Build Path to add it to the project directory library file in the Referenced Libraries directory for calling