首页 > 代码库 > java操作数据库

java操作数据库

/** *  */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 = http://www.mamicode.com/new ArrayList();"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 =http://www.mamicode.com/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操作数据库