以下展示的为JAVA使用jdbc连接MYSQL简单示例:
1 import java.sql.DriverManager; 2 import java.sql.ResultSet; 3 import java.sql.SQLException; 4 5 import com.mysql.jdbc.Connection; 6 import com.mysql.jdbc.Statement; 7 8 public class MysqlDBManager { 9 // 驱动程序名 10 private static String DBDRIVER = "com.mysql.jdbc.Driver"; 11 // URL指向要访问的数据库名 12 private static String SERVERURL = ""; 13 // MySQL配置时的用户名 14 private static String USER = ""; 15 // MySQL配置时的密码 16 private static String PASSWORD = ""; 17 //连接对象 18 private Connection conn = null; 19 // 20 private Statement stmt = null; 21 //设计为单例模式 22 private static MysqlDBManager uniqueInstance = null; 23 24 private MysqlDBManager() { 25 ReadProperty readUtil = new ReadProperty(); 26 SERVERURL = "jdbc:mysql://"+readUtil.getProperties("host")+":3306/"+readUtil.getProperties("database"); 27 USER = readUtil.getProperties("user"); 28 PASSWORD = readUtil.getProperties("password")==null?"":readUtil.getProperties("password"); 29 initConnect(); 30 } 31 32 public static MysqlDBManager getInstance() { 33 if (uniqueInstance == null) { 34 uniqueInstance = new MysqlDBManager(); 35 } 36 return uniqueInstance; 37 } 38 /** 39 * 初始化数据库连接 40 */ 41 private void initConnect() { 42 if (null == conn) { 43 // 加载驱动程序 44 try { 45 Class.forName(DBDRIVER); 46 // 连续数据库 47 conn = (Connection) DriverManager.getConnection(SERVERURL,USER, PASSWORD); 48 stmt = (Statement)conn.createStatement(); 49 } catch (ClassNotFoundException e) { 50 System.out.println("Can`t find the mysql Driver!"); 51 } catch (SQLException e) { 52 System.out.println("Can`t connect to mysql DB"); 53 } 54 } 55 } 56 /** 57 * 获取连接实例 58 * @return 59 */ 60 private Statement getDBManager(){ 61 if(null == stmt){ 62 initConnect(); 63 } 64 return stmt; 65 } 66 /** 67 * 执行查询SQL语句 68 * @param sql 69 * @return 70 */ 71 public ResultSet executeQuery(String sql){ 72 ResultSet rs = null; 73 try { 74 rs = getDBManager().executeQuery(sql); 75 } catch (SQLException e) { 76 System.out.println("Excute sql error"); 77 } 78 return rs; 79 } 80 /** 81 * 执行update,insert语句 82 * @param sql 83 * @return 84 */ 85 public int excuteUpdate(String sql){ 86 int executeUpdate = 0; 87 try { 88 executeUpdate = getDBManager().executeUpdate(sql); 89 } catch (SQLException e) { 90 System.out.println("Excute sql error"); 91 } 92 return executeUpdate; 93 } 94 95 /** 96 * 批量执行执行update,insert语句 97 * @param sql 98 * @return 99 */ 100 public int batchUpdate(String[] sql){ 101 try { 102 for(String s : sql){ 103 if(s == null || "".equals(s)) 104 continue; 105 getDBManager().addBatch(s); 106 } 107 int[] executeBatch = getDBManager().executeBatch(); 108 return executeBatch.length; 109 } catch (SQLException e) { 110 System.out.println("Excute sql error"); 111 } 112 return 0; 113 } 114 115 }
欢迎加入Hadoop技术群进行交流:147681830