在做JAVA数据库开发时,可能因数据库的驱动方式导致连接数据库出现麻烦!可能你使用的是连接池等其他技术,在你准备写数据库操作代码时,不妨试试用最原始的方式测测你的数据库是否配置正确!以下代码是在命令行窗口下进行编辑、运行,会给你在接下来的数据库开发省去不必要的麻烦~~~~!
——————————————————————————————————————————————
import java.sql.*;
public class DBConnectTest{
private Connection m_conn;
private Statement m_stmt;
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:cpmis";
String uName = "zjnx";
String uPwd = "zjnx";
/**
*
*/
public DBConnectTest() {
if(this.setDriver(driver))
{
if(this.setConnection(url, uName, uPwd))System.out.println("连接数据库成功");
else System.out.println("连接数据库失败");
}
}
public DBConnectTest(String driver, String url, String userName, String userPWD) {
try {
m_conn = DriverManager.getConnection(url, userName, userPWD);
m_stmt = m_conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean setDriver(String driver) {
try {
Class.forName(driver);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean setConnection(String url, String userName, String userPWD) {
try {
m_conn = DriverManager.getConnection(url, userName, userPWD);
m_stmt = m_conn.createStatement();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// 处理查询
public ResultSet sendQuery(String sql) {
try {
ResultSet m_rs = m_stmt.executeQuery(sql);
return m_rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
// 处理数据更新
public int sendUpdate(String sql) {
try {
return m_stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
// 测试程序
public static void main(String[] arg) {
DBConnectTest db = new DBConnectTest();
ResultSet rs = db.sendQuery("select * from USER_LOGIN where USERID='ccmis'");
try {
if (rs != null) {
while (rs.next()) {
System.out.println(rs.getString("USERID") + " "
+ rs.getString("PASSWORD"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
//System.out.println("adf");
}
}