1. 获取数据库连接和查询代码
package connectionmysql; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class ConnectionMysql { //数据库连接用户名
private String userName = "root"; //数据库连接密码
private String pwd = "910214"; //设置数据库
private String database = "jsp"; //设置jdbc驱动
private String dbDriver = "com.mysql.jdbc.Driver"; //设置数据库连接URL
private String dbConnect = "jdbc:mysql://localhost:3306/"+database; //连接变量
private Connection conn = null; private Statement stmt = null; ResultSet rs = null; /*数据库驱动注册*/
public ConnectionMysql()
{
try{
Class.forName(dbDriver);
}
catch(Exception ex)
{
System.out.println("连接失败: "+ex.getMessage());
}
} /*建立数据库连接及其数据查询*/
public ResultSet executeQuery(String sql) throws SQLException{
rs = null;
try{
conn = DriverManager.getConnection(dbConnect, userName, pwd);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}catch(Exception ex)
{
System.out.println("连接失败: "+ex.getMessage());
}
// finally{
// //关闭数据库连接
// stmt.close();
// conn.close();
// }
return rs;
} /*建立数据库连接和数据库查询*/
public void excuteUpdate(String sql) throws SQLException
{
stmt = null;
try{
//连接数据库
conn = DriverManager.getConnection(dbConnect, userName, pwd);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
}catch(Exception ex){
//手动抛出异常
throw new SQLException(ex.getMessage());
}
// finally{
// stmt.close();
// conn.close();
// }
} /*
* 考虑数据库的性能问题,需要释放数据库资源,因此关闭方法
*/
//关闭陈述语句
public void CloseStmt()
{
try{
stmt.close();
}catch(SQLException ex){
System.out.println("关闭数据库失败: "+ex.getMessage());
}
}
//关闭连接
public void CloseConn(){
try{
conn.close();
}catch(SQLException ex){
System.out.println("关闭连接失败: "+ex.getMessage());
}
} }
2.测试代码
package connectionmysql; import java.sql.ResultSet;
import java.sql.SQLException; public class TestMysqlConnection { /**
* 运行程序测试
*/
public static void main(String[] args) {
// TODO Auto-generated method stub ConnectionMysql conMysql = new ConnectionMysql();
//查询数据库SQL语句
String sql = "select username,password from userlogin"; try{
//返回查询结果集
ResultSet rs = conMysql.executeQuery(sql);
//打印查询数据
if(rs.next()){
String username = rs.getString(1);
String password = rs.getString(2);
System.out.println("用户名: "+username);
System.out.println("密 码 : "+password);
// System.out.println(rs.getString(2));
}
}catch(SQLException ex){
System.out.println("查询失败: "+ex.getMessage());
}finally{
//关闭数据库连接
conMysql.CloseStmt();
conMysql.CloseConn();
}
} }