- JDBC连接图
- 加载mySQL驱动包:
工程名上点击右键-Properties(属性)-Java Build Path(Java构建路径)-Libraries()-Add External JARs(添加JAR)-找到一个mysql-connector-java-5.0.7-bin.jar添加上就行了
在myEclipse(内部启动Tomcat)中调试程序过程中爆出java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver错误。经过搜索得知,新建的项目,虽然在Tomcat的common/lib文件夹中,项目的WEB-INF/lib中都有mysql-connector-java-5.0.3-bin.jar,但是在Eclipse的这个工程中没有添加。 so,解决办法是工程名上点击右键-Properties(属性)-Java Build Path(Java构建路径)-Libraries()-Add External JARs(添加JAR)-找到一个mysql-connector-java-5.0.7-bin.jar添加上就行了.
-
/** * */ package com.lh.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author huanli2 * */ public class test { private static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; private static final String DBURL = "jdbc:mysql://localhost:3306/mydb"; private static final String DBUSER = "root"; private static final String DBPASSWORD = "root"; private static Connection conn = null; private static PreparedStatement pstmt = null; public static void main(String[] args){ try{ Class.forName(DBDRIVER);//加载驱动程序 }catch(Exception e){ e.printStackTrace(); } try { conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);//获取连接 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = "SELECT name FROM info"; try { pstmt=conn.prepareStatement(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ResultSet rs = pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }