随笔 - 28  文章 - 2  评论 - 0  阅读 - 10645

javaweb之eclipse工程连接mysql数据库

javaweb之eclipse工程连接mysql数据库

准备工作:
1.在mysql官网下载mysqlconnection的jar包

输入网址:mysql.com—点击DOWNLOADS——下拉选择MySQL Community (GPL) Downloads »——选择Connector/J——下载后解压——找到mysql-connector-java-8.0.22.jar

2.将mysql-connector-java-8.0.22.jar复制到当前javaweb工程

3.构建路径:右击当前项目——选择Build Path——Configure Build Path——Libraries——AddJARs——将之前复制在lib文件下的mysql-connection导入——Apply and Close

看到如下则成功:

4.在src中创建com.mysqlconnection包和mysqlconnection类

进行连接

public class mysqlconnect {
	public static void main(String[] args) {
        //判断驱动是否加载成功
		try {
			Class.forName("com.mysql.cj.jdbc.Driver"); //固定语法
			System.out.print("成功加载驱动!");//提示语
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.print("加载驱动失败!");
			e.printStackTrace();
		}
        //连接mysql
		Connection con;   
        //localhost为主机名  3306为mysql的端口号   web:进行连接的目标数据库  
		String url = "jdbc:mysql://localhost:3306/web?serverTimezone=UTC";
        //登录数据库用户名
		String user = "root";
        //登录数据库的密码
		String password = "password";
		try {
			con = DriverManager.getConnection(url,user,password); //将参数传给驱动进行连接
			if(!con.isClosed()) {
				System.out.print("成功连接数据库!");
                //创建statement对象
				Statement statement = con.createStatement();
                //声明一个sql语句查询student表中所有信息
				String sql = "select * from student";
				ResultSet rs = statement.executeQuery(sql);
                //循环输出打印student表中的id name age
				while (rs.next()){System.out.print(rs.getString("id"));
				System.out.print("");
				System.out.print(rs.getString("name"));
				System.out.print("");
				System.out.print(rs.getString("age"));
				System.out.print("\t");}			
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}


	}

}



posted on   clinch  阅读(1463)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示