JDBC—CRUD操作

版权声明:. https://blog.csdn.net/WildestDeram/article/details/89602342

CRUD操作

CRUD指的是增删改查操作

  • 向数据库中保证记录
  • 修改数据库中的记录
  • 删除数据库中的记录
  • 查询数据库中的记录
package com.dream.demo1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

public class JDBC_CRUD {
	
	/**
	 * 数据保存操作
	 */
	@Test
	public void test() {
		// 定义Connection Statement 对象
		Connection conn = null;
		Statement stat = null;
		
		try {
			// 1.连接数据库
			conn = DriverManager.getConnection("jdbc:mysql:///jdbctest"+
			"?useSSL=false&serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf-8"
			, "root", "1916");
			
			// 2.编写SQL语句
			String sql = "insert user values (null,'eee','555','七七')";
			
			// 3.执行SQL语句
			stat = conn.createStatement();
			
			// 添加操作使用executeUpdate();
			int i = stat.executeUpdate(sql);
			if(i>0) {
				System.out.println("数据已存入!");
			}
		} catch (Exception e) {
			// 打印错误信息
			e.printStackTrace();
		} finally {
			// 关闭资源
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				conn=null;
			}
			
			if(stat!=null) {
				try {
					stat.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				stat=null;
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/WildestDeram/article/details/89602342