单独java 程序连接Mysql数据库

编辑器加载中...步骤: 1.下载安装mysql

2.下载mysql驱动的jar包,我的版本为:mysql-connector-java-5.1.10-bin.jar

 3.讲上面的jar包文件复制到jdk安装目录,D:\Program Files\Java\jdk1.6.0_23\jre\lib\ext 下面,我的安装目录是D盘,其他盘类似。

 4.修改环境变量classpath,添加下面的内容: ;D:\Program Files\Java\jdk1.6.0_23\jre\lib\ext\mysql-connector-java-5.1.10-bin.jar , 即jar包目录和jar包文件名字。

 5.写代码测试 代码如下:

/** * 单独的java程序连接mysql数据库

* author:JavaAlpha

* date :2011-3-31 20:48:28

* IDE:EmEditor Version 9.16

*/

import java.sql.*;

 public class Test {

 public static void main(String[] args){

String driver = "com.mysql.jdbc.Driver";

String url = "jdbc:mysql://127.0.0.1:3306/test";

String user = "root";

 String password = "123456";

try {

Class.forName(driver);

Connection conn = DriverManager.getConnection(url, user, password);

 if(!conn.isClosed())

System.out.println("Succeeded connecting to the Database!");

 Statement statement = conn.createStatement();

 String sql = "select * from t_user order by id desc";

ResultSet rs = statement.executeQuery(sql);

 String name = null;

while(rs.next()) {

name = rs.getString("sourse");

 System.out.println(rs.getString("id")+"\t"+rs.getString("href") + "\t" + name + "\t" + rs.getString("title")+"\t"+rs.getString("time"));

 }

 rs.close();

conn.close();

} catch(ClassNotFoundException e) {

System.out.println("Sorry,can`t find the Driver!");

e.printStackTrace();

 } catch(SQLException e) {

e.printStackTrace();

} catch(Exception e) {

e.printStackTrace();

  }

  }

}

posted @ 2011-05-07 19:31  Hongten  阅读(921)  评论(0编辑  收藏  举报
Fork me on GitHub