mysqlデータベースのカプセル化
1587 ワード
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Dao {
protected static Connection cnt = null;
protected static Statement stmt;
protected static ResultSet rs;
protected static String dbClassName = "org.gjt.mm.mysql.Driver";
/*
*
*/
protected Dao() {
if (cnt == null) {
try {
Class.forName(dbClassName);
cnt = DriverManager
.getConnection("jdbc:mysql://localhost/dataname?"
+ "user=users&password=key");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException s) {
System.out.print(" ");
s.printStackTrace();
}
} else
return;
}
/*
*
*/
public static ResultSet executeQuery(String sql) {
try {
if (cnt == null)
new Dao();
return (cnt.createStatement().executeQuery(sql));
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
}
}
/*
* ( )
*/
public static int executeUpdate(String sql) {
try {
if (cnt == null)
new Dao();
return cnt.createStatement().executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
return -1;
} finally {
}
}
/*
* ,
*/
public static void CloseAll() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (cnt != null) {
cnt.close();
cnt = null;
}
} catch (SQLException ac) {
ac.printStackTrace();
}
}
}