JAVA-JDBC连接和相关学习

JAVA-JDBC连接和相关学习

JDBC基本连接方式

首先准备工作下载安装Mysql或者其他数据库,其次导入 mysql-connector-java-5.0.8-bin.jar 或其他第三方包(用于驱动)

然后连接:

	Connection connection = null;
	PreparedStatement preparedStatement = null;
	//第一步加载驱动;
Class.forName("com.mysql.jdbc.Driver");
 	//第二步获取连接;
// 建立与数据库的Connection连接
// 这里需要提供:
// 数据库所处于的ip:127.0.0.1 (本机)本地可以写local:
// 数据库的端口号: 3306 (mysql专用端口号)
// 数据库名称 weeklyreport
// 编码方式 UTF-8
//serverTimezone最好加一下,因为有时候会报错;
//useSSL=false
//MySQL在高版本需要指明是否进行SSL连接
//1.true 需要连接
//2.false 不需要连接
String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";//自己的密码
			connection = DriverManager.getConnection(url, user, password);
	//创建statement或者preparedStatement,先用preparedStatement举例;
	String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setString(2, password2);
			preparedStatement.setString(3,date);
			preparedStatement.executeUpdate();
	//这就实现了一个插入注册信息的操作
	//最后一步要实现关闭connection和preparedStatement操作;
	connection.close();
	preparedStatement.close();

完整的就是

Connection connection = null;
PreparedStatement preparedStatement = null;
try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";//自己的密码
			connection = DriverManager.getConnection(url, user, password);
			String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setString(2, password2);
			preparedStatement.setString(3,date);
			preparedStatement.executeUpdate();
			}catch (ClassNotFoundException e) {
    
    
				 e.printStackTrace();
			} catch (SQLException e){
    
    
				 e.printStackTrace();
			} finally {
    
    
				try {
    
    
                    //一般preparedStatement关闭在connection关闭之后;
					connection.close();
					preparedStatement.close();
				} catch (SQLException e){
    
    
					 e.printStackTrace();
				}
			}
	}

SQL语句

1、sql还有很多其他的操作,例如增删改查

//增加
 String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
//删除 
 String sql = "delete from hero where id = 5";
//更改
 String sql = "update hero set name = 'name 5' where id = 3";

具体的其他操作可以参考菜鸟教程mysql里语句的具体用法

2、较为特殊的是查询操作;

public boolean finduser(String name2,String password2) {
    
    
		ResultSet result = null;
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		int i =0;
		try {
    
    
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
			String user = "root";
			String password = "password";
			connection = DriverManager.getConnection(url, user, password);
			String sql = "select * from users2 where USER_NAME= ? and USER_PASSWORD= ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name2);
			preparedStatement.setString(2, password2);
            //特殊的就是要设置一个结果集ResultSet,把结果存放在结果集中,
			result =preparedStatement.executeQuery();
			while(result.next()) {
    
    
				i++;
			 }
            //这里实现的功能就是在登陆的时候验证账号和密码,如果正确,那查询得到的结果集就有内容并i++最后返回true;
			}catch (ClassNotFoundException e) {
    
    
				 e.printStackTrace();
			} catch (SQLException e){
    
    
				 e.printStackTrace();
			} finally {
    
    
				try {
    
    
					connection.close();
					preparedStatement.close();
					result.close();
                    //关闭结果集
				} catch (SQLException e){
    
    
					 e.printStackTrace();
				}
			}
		if (i == 0)
			return false;
		else 
			return true;
	}

具体的其他操作可以参考菜鸟教程mysql里语句的具体用法

Statement和preparedStatement区别

1、

Statement 需要进行字符串拼接,可读性和维护性比较差 ;

PreparedStatement 使用参数设置,可读性好,不易犯错 ;

			Statement s = connection.createStatement();
            PreparedStatement  preparedStatement= connection.prepareStatement(sql);
            // Statement需要进行字符串拼接,可读性和维修性比较差
            String sql0 = "insert into USERS1(null," + "'学生1'" + "," + "'123456'"+")";
            s.execute(sql0);
            String sql = "insert into USERS1(null,?,?,?)";
            // PreparedStatement 使用参数设置,可读性好,不易犯错
            // "insert into USERS1(null,?,?)";
            preparedStatement.setString(1, "学生1");
            preparedStatement.setString(2, "123456");
            preparedStatement.execute();

2、 PreparedStatement有预编译机制,性能比Statement更快

​ 数据库对带?的SQL进行预编译

​ 每次执行,只需要传输参数到数据库端

  1. 网络传输量比Statement更小
  2. 数据库不需要再进行编译,响应更快

3、 PreparedStatement防止SQL注入式攻击, 比如登录时密码加入OR 1=1就会被sql读取并登录;

execute与executeUpdate的区别

1、 executeexecuteUpdate的相同点:都可以执行增加,删除,修改

preparedStatement.execute();
preparedStatement.executeUpdate();

2、不同:
execute可以执行查询语句
然后通过getResultSet,把结果集取出来
executeUpdate不能执行查询语句
不同2:
execute返回boolean类型,true表示执行的是查询语句,false表示执行的是insert,delete,update等等
executeUpdate返回的是int,表示有多少条数据受到了影响

事务

  			connection.setAutoCommit(false);
  
            // 更改操作
            String sql1 = "update hero set hp = hp +1 where id = "xuesheng1"";
            statement.execute(sql1);
  
         
           //第二个更新操作 
           // 不小心写错写成了 updata(而非update)
            String sql2 = "updata users1 set score = score -1 where name = "xuesheng2"";
            statement.execute(sql2);
  
            // 手动提交
            connection.commit();

所以放在

connection.setAutoCommit(false);

connection.commit();

之间的事务只要一个操作有错误,那么全都不会进行,这样可以保证差错不出现;

ORM

其实就是建立一个对象其属性可以存储数据库里的一条记录然后展开操作;

ORM=Object Relationship Database Mapping

对象和关系数据库的映射

简单说,一个对象,对应数据库里的一条记录

DAO

实际上就是运用ORM的思路,把数据库相关的操作都封装在这个类里面,其他地方看不到JDBC的代码

数据库连接池

提前创建数条连接,待线程使用,如果全部被使用,没能使用的线程就等待连接用完重新回到数据库连接池;并且, 这些连接都不会关闭,而是不断的被循环使用,从而节约了启动和关闭连接的时间。

package jdbc;
  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
  
public class ConnectionPool {
    
    
  
    List<Connection> cs = new ArrayList<Connection>();
  
    int size;
  
    public ConnectionPool(int size) {
    
    
        this.size = size;
        init();
    }
  
    public void init() {
    
    
          
        //这里恰恰不能使用try-with-resource的方式,因为这些连接都需要是"活"的,不要被自动关闭了
        try {
    
    
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < size; i++) {
    
    
                Connection c = DriverManager
                        .getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
  
                cs.add(c);
  
            }
        } catch (ClassNotFoundException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  
    public synchronized Connection getConnection() {
    
    
        while (cs.isEmpty()) {
    
    
            try {
    
    
                this.wait();
            } catch (InterruptedException e) {
    
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Connection c = cs.remove(0);
        return c;
    }
  
    public synchronized void returnConnection(Connection c) {
    
    
        cs.add(c);
        this.notifyAll();
    }
  
}
//代码来自how2j网站


猜你喜欢

转载自blog.csdn.net/jnh1234/article/details/109425961