Java连接数据库

使用JDBC连接MySQL数据库

import java.sql.*;

public class test1 {
    //JDBC 驱动名及数据库 URL
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost:3306/test1";//test1为库的名称
	 //数据库的用户名与密码
	static final String USER = "root";
	static final String PASS = "";
	
	public static void main(String args[]) {
		Connection conn = null;
		Statement stmt = null;
		try {
			//注册JDBC驱动
			Class.forName("com.mysql.jdbc.Driver");
			//打开链接
			System.out.println("打开数据库...");
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			//执行查询
			System.out.println(" 实例化Statement对象...");
			stmt = conn.createStatement();
			String sql = "select id,name,url from websites";
			ResultSet re = stmt.executeQuery(sql);
			//展开结果集数据库
			while(re.next()) {
				// 通过字段检索
				int id = re.getInt("id");
				String name = re.getString("name");
				String url = re.getString("url");
				//输出数据
				System.out.print("ID: " + id);
				System.out.print(", 站点名称: " + name);
				System.out.print(", 站点 URL: " + url);
				System.out.print("\n");
			}
			//完成后关闭
			re.close();//关闭记录集 
			stmt.close();//关闭声明 
			conn.close();//关闭连接对象 
		}catch(SQLException se) {//处理JDBC错误
			se.printStackTrace();
		}catch(Exception e) {//处理Class.forName错误
			e.printStackTrace();
		}finally {
			//关闭资源
			try {//关闭声明 
				if(stmt != null) {
					stmt.close();
				}
			}catch(SQLException se2) {
				
			}
			try {//关闭连接对象 
				if(conn != null) {
					conn.close();
				}
			}catch(SQLException se) {
				se.printStackTrace();
			}
		}
		System.out.println("GoodBye!");
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值