java 操作数据库
最近开始学习 jsp+servlet web开发, 操作数据库必不可少,此文章详细记录了java 连接mysql的步骤
1.下载mysql-connector-java-3.1.10-bin 这个jar包,然后引入
2 建立jdbc对象
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(this.dbName,this.userName,this.userPasswd);
3创建 Statement 对象,用于操作执行sql语句
Statement stmt = conn.createStatement();
4.执行sql 返回结果集(select)
ResultSet rs = stmt.executeQuery(sql);
5.操作结果集
每天数据存为haspmap后放入list
自己简单的封装了一下,代码如下
package database;
import java.sql.*;
import java.util.*;
import com.alibaba.fastjson.JSONObject;
public class DbClass {
//成员属性
private String userName;
private String userPasswd;
private String dbName;
//成员方法
public void setParam(String url,String user,String password){
this.userName = user;
this.userPasswd = password;
this.dbName = "jdbc:mysql://localhost/"+url;
}
//执行查询的sql
public ArrayList selectQuery(String sql){
ArrayList list = new ArrayList();
try{
//加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的连接
Connection conn = DriverManager.getConnection(this.dbName,this.userName,this.userPasswd);
Statement stmt = conn.createStatement();//创建语句对象,用以执行sql语言
ResultSet rs = stmt.executeQuery(sql);
//获取总列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount(); //总供的字段数
//list数组
Map rowData = new HashMap();
//处理结果集 存入list数组
while (rs.next())
{
rowData = new HashMap(columnCount);
for(int i=1;i<=columnCount;i++){
String columnName = metaData.getColumnName(i); //获取每个字段
String value = rs.getString(columnName); //根据字段名称获取值
rowData.put(columnName,value); //放入map
}
list.add(rowData); //放入list
}
rs.close();//关闭数据库
conn.close();
}catch(Exception ex){
System.out.println("Error : " + ex.toString());
}
return list;
}