使用java连接mysql数据库

package com.ru.dao;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class MySqlHelper {
public Connection ct = null;
public Statement st = null;
private ResultSet rs = null;
//数据操作返回rs
public  ResultSet executeQuery(String sql) {
// 创建数据库变量


try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/ru",
"root", "123456");
// 创建表达式
st = ct.createStatement();
// 执行sql语句
rs = st.executeQuery(sql);


} catch (Exception e) {
e.printStackTrace();
} 
return rs;
}
//关闭资源
public void close(ResultSet rs,Statement st,Connection ct){
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
// TODO: handle exception
}


} else if (st != null) {
try {
st.close();
} catch (Exception e) {
// TODO: handle exception
}


} else if (ct != null) {
try {
ct.close();
} catch (Exception e) {
// TODO: handle exception
}


}
}
 
}

猜你喜欢

转载自tydldd.iteye.com/blog/1829515