Java MySql 连接数据库

工具:eclipse、MySql、Navicat Premium、

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

public class JDBCDemo2 {

	private static final String USERNAME = "root";
	private static final String PWD = "lwx";

	private static final String dbName = "rzw"; // 数据库名
	private static final String url1 = "jdbc:mysql://localhost:3306/" + dbName;
	private static final String url2 = "?user=" + USERNAME + "&password=" + PWD;
	private static final String url3 = "&useUnicode=true&characterEncoding=GB2312";
	private static final String URL = url1 + url2 + url3; // 形成带数据库读写编码的数据库连接字

	// 此方法实现对数据库的增删改查 增删改 一般 是 update(); 查 单独
	public static void update() {// 增删改
		Connection connection = null;
		Statement stmt = null;
		try {
			// a.导入驱动,加载具体的驱动类
			Class.forName("com.mysql.jdbc.Driver");// 加载具体的驱动类
			// b.与数据库建立连接
			connection = DriverManager.getConnection(URL, USERNAME, PWD);
			// c.发送sql,执行(增删改、查)
			stmt = connection.createStatement();
//			String sql = "update student set STUNAME='ls' where stuno=1";
//			String sql = "delete from student where stuno=1";
			// 执行SQL
			String sql = "Insert into stu_info values(17,'zs','男',20,70,177)";
			
			int count = stmt.executeUpdate(sql); // 返回值表示 增删改 几条数据
			// d.处理结果
			if (count > 0) {
				System.out.println("操作成功!");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();// 对象.方法
				if (connection != null)
					connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		update();
	}
}

在这里插入图片描述
在这里插入图片描述

发布了14 篇原创文章 · 获赞 28 · 访问量 3045

猜你喜欢

转载自blog.csdn.net/weixin_44949135/article/details/104440149
今日推荐