java写入数据 加锁操作

	public static void main(String args[]) {
		Connection connMySQL = null;
		Statement stmt = null;
			String strJDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  //java8的链接写法,java5把cj.去掉就行
            String strDB_URL = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=false&character_set_server=utf8mb4";
            String strMysqlUser = "root";  //数据库用户名
            String strMysqlPwd = "123456"; //数据库用户密码
		try {
			Class.forName(strJDBC_DRIVER);
			connMySQL = DriverManager.getConnection(strDB_URL,strMysqlUser,strMysqlPwd);
            
			connMySQL.setAutoCommit(false);   // 用事物的方式去给表加锁
			
			stmt=connMySQL.createStatement();
			
			stmt.execute("lock tables table_name write");  // 加锁,table_name是需要被你加锁的表名,记得替换
			
			stmt.execute("你的SQL语句"	); // 你要执行的SQL语句
			connMySQL.commit();   // 提交事物,在提交事物时候,你加的锁自动解除 (详细信息可以看JDBC手册)
			connMySQL.close();
			stmt.close();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
	}

 

posted @ 2023-07-15 22:20  涂山树下  阅读(38)  评论(0)    收藏  举报