Java连接数据库,基本传输操作

需要先下载mysql-connector-java-8.0.23.jar或者其他版本的jar包,如果有需要的小伙伴欢迎私信,博主私发。
下载好后把该文件复制到/Java0402/WebContent下的/Java0402/WebContent/WEB-INF中的lib文件下。
在这里插入图片描述
添加完成后会在Referenced_Libraries下有该jar包,如下图。
在这里插入图片描述
此时在保中建立一个类。
书写代码。

@Test
	public void test2() {
		// 通过数据库的链接执行CUD
		// 得到数据库连接
		Connection connection = getConnection();
		if (connection != null) {
			// 通过连接生成Statment对象
			Statement statement = null;
			try {
				statement = connection.createStatement();
				String sql = "INSERT INTO tb_user(USER_NAME,USER_AGE,USER_BIRTHDAY)VALUES('李四',21,'1990-10-15')";
				// executeUpdate传输sql语句,返回的是受影响的行数
				// statement声明;execute执行
				int t = statement.executeUpdate(sql);
				System.out.println("受影响的行数是" + t);
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				// 自动垃圾回收机制不能回收数据库的连接和执行语句
				// 先打开的后关闭
				try {
					if (statement != null) {
						statement.close();
					}
					if (connection != null) {
						connection.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 加载驱动(加载驱动一般需要写在静态代码块中,以保证这个驱动只加载一次)
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 自定义一个连接数据库的方法
	private Connection getConnection() {
		Connection connection = null;
		try {
			// 连接数据库的url,注意修改数据库的名称
			// 两种方法(url无需记忆)
			// String url =
			// "jdbc:mysql://localhost:3306/java0402?useUnicode=true&characterEncoding=UTF-8";
			String url = "jdbc:mysql://localhost:3306/java0402?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=true&allowMultiQueries=true";
			String user = "root";
			String password = "wang";
			connection = DriverManager.getConnection(url, user, password);
			System.out.println(connection.toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值