jdbc连接mysql进行增加数据,更新数据,删除数据

2022-11-13 10:58:14 浏览数 (1)

mysql8.0以上大家一定加载8.0的驱动才不会报错,或者出现连接的时候出现null,8.0多了个时区的玩意(一定要特别注意)

看代码:

代码语言:javascript复制
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.PseudoColumnUsage;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Test;

import com.mysql.cj.jdbc.Driver;
import com.mysql.cj.x.protobuf.MysqlxPrepare.Prepare;

public class connection {
		public static Connection getuser () 
		{
			Connection conn = null;
			try {
				Driver driver=new Driver();//加载驱动
				String use="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
				/*
				 * 3306:端口号
				 * test:连接数据库
				 */
				Properties infoProperties=new Properties();
				infoProperties.setProperty("user","root");
				/*用户名称*/
				infoProperties.setProperty("password","root");
				/* 用户密码*/
				conn = driver.connect(use, infoProperties);
			} catch (SQLException e) {
				
				e.printStackTrace();
			}
			return conn;
		}
		@Test
		public void test01()
		{
				Connection conn=getuser();
				System.out.println(conn);
		}
		@Test
		public void test02() //插入数据
		{
			Connection conn=getuser();
			String sql=" INSERT INTO customers(id,`name`,email) value(?,?,?)"; //占位符处理
			PreparedStatement ps = null;
			try {
				//预编译
				ps = conn.prepareStatement(sql);
				ps.setInt(1, 22);
				ps.setString(2,"李太白");
				ps.setString(3,"2860467163.@qqcom");
				ps.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {//关闭连接
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		@Test
		public void test03()
		{
			Connection conn=getuser();
			String sql="update customers set email=? where id=?";
			PreparedStatement ps = null;
			try {
				ps = conn.prepareStatement(sql);
				ps.setString(1,"2860467163.@qqcom");
				ps.setInt(2, 1);
				ps.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		@Test
		public void test04()
		{
			Connection conn=getuser();
			String sql=" DELETE FROM customers WHERE id =?";
			PreparedStatement ps = null;
			try {
				ps = conn.prepareStatement(sql);
				ps.setInt(1, 22);
				ps.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
}

0 人点赞