Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Ví dụ về câu lệnh JDBC - Chèn, Xóa, Cập nhật, Chọn bản ghi

Bài viết này sẽ hướng dẫn bạn cách sử dụng java.sql.Statement để thực hiện các lệnh chèn, cập nhật, xóa và chọn các lệnh SQL DML với các ví dụ.

1. Sử dụng java.sql.Statement.execute (Chuỗi sql) để chạy lệnh chèn, cập nhật và xóa.

/* This method can be used to execute insert, update, delete dml command. */
public void executeSql(String ip, int port, String dbName, String userName, String password, String sql)
{
	/* Declare the connection and statement object. */
	Connection conn = null;
	Statement stmt = null;
	try
	{
		/* Get connection object. */
		conn = this.getMySqlConnection(ip, port, dbName, userName, password);
		
		/* Get statement object. */
		stmt = conn.createStatement();
		
		/* The method can execute insert, update and delete dml command. */
		stmt.execute(sql);
		
		System.out.println("Execute sql successfuly, " + sql);
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		this.closeDBResource(stmt, conn);
	}
}
     

/* Close statement and connection after use, this can avoid resource waste. */
public void closeDBResource(Statement stmt, Connection conn)
{
	try
	{
		if(stmt!=null)
		{
			stmt.close();
			stmt = null;
		}
		
		if(conn!=null)
		{
			conn.close();
			conn = null;
		}
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}
}

2. Chèn và trả lại các khóa được tạo tự động.

Đối với lệnh chèn, hãy sử dụng java.sql.Statement.execute(String sql, int autoGeneratedKeys) để chèn và trả về giá trị của khóa tăng tự động, đó là giá trị id trong ví dụ này.

/* Execute insert command and return the auto generated record id. */
public int executeInsertSql(String ip, int port, String dbName, String userName, String password, String sql)
{
	int ret = -1;
	/* Declare the connection and statement object. */
	Connection conn = null;
	Statement stmt = null;
	try
	{
		/* Get connection object. */
		conn = this.getMySqlConnection(ip, port, dbName, userName, password);
		
		/* Get statement object. */
		stmt = conn.createStatement();
		
		/* The method can execute insert dml command and return auto generated key values. */
		stmt.execute(sql, Statement.RETURN_GENERATED_KEYS);
		
		ResultSet rs = stmt.getGeneratedKeys();
			
		if(rs.next())
		{
			/* Please note the index start from 1 not 0. */
			ret = rs.getInt(1);
		}			
		
		System.out.println("Execute sql successfuly, " + sql);
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		this.closeDBResource(stmt, conn);
		return ret;
	}
	
}

3. Thực thi lệnh SQL select.

/* This method can be used to execute select dml command. */
public List executeSelectSql(String ip, int port, String dbName, String userName, String password, String selectSql)
{
	List ret = new ArrayList();
	/* Declare the connection and statement object. */
	Connection conn = null;
	Statement stmt = null;
	try
	{
		/* Get connection object. */
		conn = this.getMySqlConnection(ip, port, dbName, userName, password);
		
		/* Get statement object. */
		stmt = conn.createStatement();
		
		/* The method can execute select dml command. */
		ResultSet rs = stmt.executeQuery(selectSql);
		
		if(rs!=null)
		{
			while(rs.next())
			{
				int teacherId = rs.getInt("id");
				
				String teacherName = rs.getString("name");
				
				String teahcerEmail = rs.getString("email");
			
				TeacherDTO teacherDto = new TeacherDTO();
				
				teacherDto.setId(teacherId);
				
				teacherDto.setName(teacherName);
				
				teacherDto.setEmail(teahcerEmail);
				
				ret.add(teacherDto);
				
				System.out.println("id = " + teacherDto.getId());
				System.out.println("name = " + teacherDto.getName());
				System.out.println("email = " + teacherDto.getEmail());
				System.out.println("**************************************");
			}
		}
		
		System.out.println("Execute sql successfuly, " + selectSql);
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		this.closeDBResource(stmt, conn);
		return ret;
	}

}

4. TeacherDTO.java.

Lớp này được sử dụng để lưu một bản ghi dữ liệu trong bảng giáo viên.

package com.dev2qa.java.jdbc;

/* This class represent one record in database teacher table. */
public class TeacherDTO {
	
	private int id;
	
	private String name;
	
	private String email;

	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 getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}

5. Hoàn thành mã mẫu.

  1. Ví dụ này sẽ sử dụng cơ sở dữ liệu MySQL kiểm tra và bảng giáo viên , giáo viên bảng có ba cột, chúng là id , tên, email . Bạn có thể tham khảo Tuyên bố Sử dụng Ví dụ Tạo Bảng của JDBC để tìm hiểu thêm.
  2. Bạn có thể tạo bảng giáo viên trong phpMyAdmin. Bạn cần thêm tên cột là id , loại là int, và kiểm tra A_I để làm cho nó tự động tăng lên.

5.1 Các bước mã mẫu:

  1. Chèn một bản ghi (xin chào, [email protected]).
  2. Chèn một bản ghi khác (hello1, [email protected]) và trả lại id bản ghi được tạo tự động.
  3. Cập nhật tên cho jerry sử dụng id bản ghi thứ hai.
  4. Truy vấn tất cả các bản ghi trong giáo viên bảng.
  5. Xóa bản ghi email nào là [email protected]
  6. Liệt kê tất cả các bản ghi trong giáo viên bảng lại.
public static void main(String[] args) {
		
	/* Below are db connection required data. */
	String ip = "localhost";
	int port = 3306;
	String dbName = "test";
	String userName = "root";
	String password = "";
	
	/* Create an instance. */
	JDBCStatementExample jdbcStatementExample = new JDBCStatementExample();
	
	/* Insert one record. */
	String insertSql = "insert into teacher(name, email) values('hello','[email protected]')";
	/* Execute the insert command. */
	jdbcStatementExample.executeSql(ip, port, dbName, userName, password, insertSql);
	
	/* Insert another record. */
	insertSql = "insert into teacher(name, email) values('hello1','[email protected]')";
	/* Execute the insert command. */
	int autoGenId = jdbcStatementExample.executeInsertSql(ip, port, dbName, userName, password, insertSql);
	
	/* update record. */
	String updateSql = "update teacher set name = 'jerry' where id = " + autoGenId;
	/* Execute the update command. */
	jdbcStatementExample.executeSql(ip, port, dbName, userName, password, updateSql);
	
	/* select records. */
	String selectSql = "select * from teacher";
	jdbcStatementExample.executeSelectSql(ip, port, dbName, userName, password, selectSql);
	
	String deleteSql = "delete from teacher where email = '[email protected]'";
	jdbcStatementExample.executeSql(ip, port, dbName, userName, password, deleteSql);
	
	/* select records after delete. */
	selectSql = "select * from teacher";
	jdbcStatementExample.executeSelectSql(ip, port, dbName, userName, password, selectSql);
}


/* This method return java.sql.Connection object from MySQL server. */
public Connection getMySqlConnection(String ip, int port, String dbName, String userName, String password)
{
	/* Declare and initialize a sql Connection variable. */
	Connection ret = null;
	
	try
	{
	
		/* Register for mysql jdbc driver class. */
		Class.forName("com.mysql.jdbc.Driver");
		
		/* Create mysql connection url. */
		String mysqlConnUrl = "jdbc:mysql://" + ip + ":" + port + "/" + dbName;
		
		/* Get the mysql Connection object. */
		ret = DriverManager.getConnection(mysqlConnUrl, userName , password);
	}catch(Exception ex)
	{
		ex.printStackTrace();
	}finally
	{
		return ret;
	}
}

Đầu ra

<terminated> JDBCStatementExamp|e [Java Application] C:\Java\jrel.B.O_131\bin\javaw.exe [Aug 28, 2017, 7:59:53 PM]
Execute sql successfuly, insert into teacher(name, email) values('hello','[email protected]')
Execute sql successfuly, insert into teacher(name, email) values('hello1','[email protected]')
Execute sql successfuly, update teacher set name = 'jerry' where id = 22
id = 21
name = hello
email = [email protected]
**************************************
id = 22
name = jerry
email = [email protected]
**************************************
Execute sql successfuly, select * from teacher
Execute sql successfuly, delete from teacher where email = '[email protected]'
id = 21
name = hello
email = [email protected]
**************************************
Execute sql successfuly, select * from teacher

  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cách xuất cơ sở dữ liệu bằng phpMyAdmin

  2. Sử dụng chế độ xem MySQL

  3. Quản lý người dùng MySQL

  4. Cảnh báo:mysql_query ():3 không phải là tài nguyên MySQL-Link hợp lệ

  5. Dấu ngoặc kép, dấu ngoặc kép và Dấu ngoặc kép trong MySQL