怎样在eclipse开发环境中连接数据库并测试连接是否成功
1)eclipse开发环境里没有集成mysql的驱动,需要从以下地址下载连接驱动程序mysql-connector-java-XX-XX-XX.zip:
http://dev.mysql.com/downloads/connector/j
2)解压,只取文件mysql-connector-java-XX.XX.XX-bin.jar,将其引用到你需要连接mysql数据库的工程里,如:我在eclipsel里建了一个测试数据库连接的工程ConMysql。具体操作如下:
在工程ConMysql上点击右键
properties->Java Build Path->Libraries
点击Add External JARS...
选取解压后的mysql-connector-java-XX.XX.XX-bin.jar
2)驱动已经导入,下面我们来写一个程序验证一下
package test1; import java.sql.*; public class MysqlJdbc { public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 //Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("Success loading Mysql Driver!"); } catch (Exception e) { System.out.print("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test1","root","Aa-12345"); //连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 System.out.println("Success connect Mysql server!"); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from stu"); //user 为你表的名称 while (rs.next()) { System.out.println(rs.getString("name")); } } catch (Exception e) { System.out.print("get data error!"); e.printStackTrace(); } } }
点击运行程序:出现以下代码则表示连接成功
Success loading Mysql Driver!
Success connect Mysql server!
npu(mysql里自己写入的内容)
时间: 2024-11-13 12:08:41