標籤:blog http os 使用 java io ar for 檔案
/** * */package com.xx.db;/** * @author
* 實現資料庫連接 * 實現資料的查詢和更新(增刪改) * 只使用一個資料庫寫死在本檔案中即可;若使用多個資料庫,可使用設定檔實現 */import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;//import org.apache.commons.lang.StringUtils;//import org.testng.annotations.Test;public class DBUtils {//驅動程式名public String DBDriver = "com.mysql.jdbc.Driver";//URL指向要訪問的資料庫名public String url = "jdbc:mysql://192.168.xx.xx:3306/DataBase";public String user = "username";public String password = "password"; /* * MySQL配置時的使用者名稱user * Java串連MySQL配置時的密碼password */public Connection connect(){try {// 載入驅動程式Class.forName(DBDriver);// 串連資料庫Connection conn = DriverManager.getConnection(url, user, password);//if(!conn.isClosed()){ //每次都列印,太煩了,所以注釋掉了//System.out.println("Succeeded connecting to the Database!");//}return conn;}catch(ClassNotFoundException e) { System.err.println("Sorry,can‘t find the Driver!"); e.printStackTrace(); return null;} catch(SQLException e) { e.printStackTrace(); return null;} catch(Exception e) { e.printStackTrace(); return null;}}/* * 擷取查詢結果ResultSet */public ResultSet selectResult(String sql) throws SQLException{// statement用來執行SQL語句Statement statement = connect().createStatement();// 要執行的SQL語句ResultSet rs = statement.executeQuery(sql); return rs;}/* * 按列擷取查詢結果 */public List<String> getStringList(String sql, String key) throws SQLException{List<String> value = new ArrayList<String>();ResultSet rs = selectResult(sql);while(rs.next()) { //選擇key這列資料value.add(rs.getString(key));} rs.close(); connect().close();return value;} //擷取SQL執行結果的條數 public int getCount(String sql, String primaryKey) throws SQLException{int count = 0;count = getStringList(sql,primaryKey).size();return count;} //更新資料庫,適用於insert, update, deletepublic boolean updateResult(String sql) throws SQLException{// statement用來執行SQL語句Statement statement = connect().createStatement();int rs = 0;// 要執行的SQL語句,為防止全表更新,要判斷SQL語句中是否有WHERE子句,insert語句不必有WHERE子句if(sql.contains("update ") || sql.contains("delete ") ){if(sql.contains(" WHERE ") || sql.contains(" where ") ){rs = statement.executeUpdate(sql);}}else if(sql.contains("insert into ")){rs = statement.executeUpdate(sql);}statement.close();connect().close();if(rs==1){return true;}else return false;}//@Test//public void test() throws SQLException{//String sql = "SELECT * FROM tableName WHERE c_username=‘user‘";//List<String> value =getStringList(sql,"username");//System.out.println(value.toString());//System.out.println(getCount(sql,"c_uid"));////String sql2 = "update shop_tableName set a=‘1101‘ WHERE username=‘user‘";//String sql3 = "insert into tableName (id,name) values (9999999,‘11‘)";//String sql4 = "delete from tableName WHERE name=‘11‘";////System.out.println(updateResult(sql3));////System.out.println(sql4.contains(" WHERE "));//} }
歡迎光臨嬌嬌家的美衣閣 http://shop105984718.taobao.com/
java操作資料庫