在小学期的学习中,我了解了myeclipse的开发环境,与mysql连接,可对数据库进行增、删、改、查等操作,以下是在myeclipse中连接数据库的代码。
package cn.neusoft.mybatis.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Dbutils {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3308/mybatis";
private static final String UNAME = "root";
private static final String UPWD = "123";
private static Connection con = null;
private static ResultSet rs = null;
private static PreparedStatement ps = null;
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void getConnection(){
try {
con = DriverManager.getConnection(URL, UNAME, UPWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void closeAll(){
if(null!=rs){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=ps){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null!=con){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static ResultSet executeQuery(String sql,Object[] obj){
getConnection();
try {
ps = con.prepareStatement(sql);
if(null!=obj){
for(int i=0;i<obj.length;i++){
ps.setObject(i+1, obj[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static int executeUpdate(String sql,Object[] obj){
int count = 0;
getConnection();
try {
ps = con.prepareStatement(sql);
if(null!=obj){
for(int i=0;i<obj.length;i++){
ps.setObject(i+1, obj[i]);
}
}
count = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeAll();
}
return count;
}
public static boolean executeCreate(String sql,Object[] obj){
getConnection();
boolean b =false;
try {
ps = con.prepareStatement(sql);
if(null!=obj){
for(int i=0;i<obj.length;i++){
ps.setObject(i+1, obj[i]);
}
b = ps.execute();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll();
}
if(b){
return true;
}
return false;
}
}