首先要把mysql的数据库连接驱动加入到工程当中
代码只要修改下sql语句、数据库、表以及用户名和密码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* Create Date:2008-9-4 下午02:27:36
*
* Author:dingkm
*
* Version: V1.0
*
* Description:对进行修改的功能进行描述
*
*
*/
public class DBConnection {
//测试主方法
public static void main(String[] args) {
DBConnection db = new DBConnection();
Connection conn = db.getConnection();
String sql = "select * from newitem";
ResultSet rs = db.getResultSet(sql, conn);
try {
while (rs.next()) {
String title = rs.getString("title");
System.out.println(title);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//得到Connection
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
// 建立到MySQL的连接
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ding", "root", "ding");
} catch (Exception e) {
System.out.println("数据库连接异常!");
e.printStackTrace();
}
return conn;
}
//得到ResultSet
public ResultSet getResultSet(String sql, Connection conn) {
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
}
执行就可以连接数据库了
posted on 2008-09-04 19:06
老丁 阅读(219)
评论(0) 编辑 收藏 所属分类:
数据库