java-Eclipse中使用JDBC连接数据库

Posted 黑魔法os

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java-Eclipse中使用JDBC连接数据库相关的知识,希望对你有一定的参考价值。

准备工作:mysql-connector-java-5.1.6-bin.jar配置


package com.job; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class yy { // JDBC 驱动器名称 和数据库地址 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; //数据库的名称为 EXAMPLE static final String DB_URL = "jdbc:mysql://localhost/EXAMPLE"; // 数据库用户和密码 static final String USER = "root"; static final String PASS = "123456"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //注册JDBC 驱动程序 Class.forName("com.mysql.jdbc.Driver"); //打开连接 System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //执行查询 System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, name, age FROM Students"; ResultSet rs = stmt.executeQuery(sql); //得到和处理结果集 while(rs.next()){ //检索 int id = rs.getInt("id"); int age = rs.getInt("age"); String name = rs.getString("name"); //显示 System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", Name: " + name); System.out.println(); } //清理环境 rs.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!"); } }

 





以上是关于java-Eclipse中使用JDBC连接数据库的主要内容,如果未能解决你的问题,请参考以下文章

数据库原理实验(openGauss) 使用JDBC连接数据库

myBatis连接MySQL报异常:No operations allowed after connection closed.Connection was implicitly closed(示例代

Java-eclipse导入jar包

Java-Eclipse 设置自动补全

Java-Eclipse 设置自动补全

轻松学Java-eclipse判断语句结构教程