转自http://blog.sina.com.cn/s/blog_8af1069601019wjv.html
感谢!
首先,到官网下载mysql-connector-java。
http://dev.mysql.com/downloads/mirror.php?id=412737
-》(点最下方的No thanks)下载mysql-connector-java-5.1.25.zip
==========================================================================================
安装:
附安装使用教程:http://database.51cto.com/art/201006/204217.htm
-》解压缩到文件夹
-》在Eclipse中用到数据库连接的工程名右键-》build path-》configure buildpath-》Libraries-》add external jars选择上述加压文件夹中的jar包mysql-connector-java-5.1.25-bin.jar加载进来。
==========================================================================================
使用代码示例:
package DBConnect;
import java.sql.*;
public class DBConnection {
public static void main(String[] args){
//驱动程序名//不固定,根据驱动
String driver ="com.mysql.jdbc.Driver";
// URL指向要访问的数据库名******
String url ="jdbc:mysql://localhost/******";
// MySQL配置时的用户名
String user = "root";
//Java连接MySQL配置时的密码******
String password ="******";
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn =DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("Succeededconnecting to the Database!");
// statement用来执行SQL语句
Statement statement =conn.createStatement();
//要执行的SQL语句id和content是表review中的项。
String sql = "select DISTINCTid ,content from review ";
ResultSet rs =statement.executeQuery(sql);
//输出id值和content值
while(rs.next()) {
System.out.println(rs.getString("id")+ "\t" + rs.getString("content"));
}
rs.close();
conn.close();
} catch(ClassNotFoundExceptione) {
System.out.println("Sorry,can`tfind the Driver!");
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
}