来自百度 :myeclipse中使用JDBC连接MySQL连接数据库,可以新建一个java文件,使用JDBC操作数据库就可以,实例如下:
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
public
class
JDBConnection {
private
final
static
String url =
"jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=utf-8"
;//配置连接数据库的用户名和密码
private
final
static
String dbDriver =
"com.mysql.jdbc.Driver"
;
//mysql的驱动程序名
private
Connection con =
null
;
// 通过构造方法加载数据库驱动
static
{
try
{
Class.forName(dbDriver).newInstance();
//利用反射实例化驱动类
}
catch
(Exception ex) {
System.out.println(
"数据库加载失败"
);
}
}
// 创建数据库连接
public
boolean
creatConnection() {
try
{
con = DriverManager.getConnection(url);
con.setAutoCommit(
true
);
//提交<a href="https://www.baidu.com/s?wd=sql%E8%AF%AD%E5%8F%A5&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YYPynLrAD3uWN9mWIBuWfY0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3En1T3n1Dzrj6s" target="_blank" class="baidu-highlight">sql语句</a>
}
catch
(SQLException e) {
System.out.println(e.getMessage());
System.out.println(
"creatConnectionError!"
);
}
return
true
;
}
// 对数据库的增加、修改和删除的操作
public
boolean
executeUpdate(String sql) {
if
(con ==
null
) {
creatConnection();
}
try
{
Statement stmt = con.createStatement();
//得到一个结果集,拿来遍历
int
iCount = stmt.executeUpdate(sql);
return
true
;
}
catch
(SQLException e) {
System.out.println(e.getMessage());
return
false
;
}
}
// 对数据库的查询操作
public
ResultSet executeQuery(String sql) {
ResultSet rs;
try
{
if
(con ==
null
) {
creatConnection();
}
Statement stmt = con.createStatement();
//得到一个结果集,拿来查询
try
{
rs = stmt.executeQuery(sql);
}
catch
(SQLException e) {
System.out.println(e.getMessage());
return
null
;
}
}
catch
(SQLException e) {
return
null
;
}
return
rs;
}
}