以下展示的为JAVA使用jdbc连接MYSQL简单示例:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException; import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement; public class MysqlDBManager {
// 驱动程序名
private static String DBDRIVER = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名
private static String SERVERURL = "";
// MySQL配置时的用户名
private static String USER = "";
// MySQL配置时的密码
private static String PASSWORD = "";
//连接对象
private Connection conn = null;
//
private Statement stmt = null;
//设计为单例模式
private static MysqlDBManager uniqueInstance = null; private MysqlDBManager() {
ReadProperty readUtil = new ReadProperty();
SERVERURL = "jdbc:mysql://"+readUtil.getProperties("host")+":3306/"+readUtil.getProperties("database");
USER = readUtil.getProperties("user");
PASSWORD = readUtil.getProperties("password")==null?"":readUtil.getProperties("password");
initConnect();
} public static MysqlDBManager getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new MysqlDBManager();
}
return uniqueInstance;
}
/**
* 初始化数据库连接
*/
private void initConnect() {
if (null == conn) {
// 加载驱动程序
try {
Class.forName(DBDRIVER);
// 连续数据库
conn = (Connection) DriverManager.getConnection(SERVERURL,USER, PASSWORD);
stmt = (Statement)conn.createStatement();
} catch (ClassNotFoundException e) {
System.out.println("Can`t find the mysql Driver!");
} catch (SQLException e) {
System.out.println("Can`t connect to mysql DB");
}
}
}
/**
* 获取连接实例
* @return
*/
private Statement getDBManager(){
if(null == stmt){
initConnect();
}
return stmt;
}
/**
* 执行查询SQL语句
* @param sql
* @return
*/
public ResultSet executeQuery(String sql){
ResultSet rs = null;
try {
rs = getDBManager().executeQuery(sql);
} catch (SQLException e) {
System.out.println("Excute sql error");
}
return rs;
}
/**
* 执行update,insert语句
* @param sql
* @return
*/
public int excuteUpdate(String sql){
int executeUpdate = 0;
try {
executeUpdate = getDBManager().executeUpdate(sql);
} catch (SQLException e) {
System.out.println("Excute sql error");
}
return executeUpdate;
} /**
* 批量执行执行update,insert语句
* @param sql
* @return
*/
public int batchUpdate(String[] sql){
try {
for(String s : sql){
if(s == null || "".equals(s))
continue;
getDBManager().addBatch(s);
}
int[] executeBatch = getDBManager().executeBatch();
return executeBatch.length;
} catch (SQLException e) {
System.out.println("Excute sql error");
}
return 0;
} }
欢迎加入Hadoop技术群进行交流:147681830