JAVA对Mysql数据库的操作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.testng.annotations.Test;
public class GetMySqlData {
public Map<Object, Object> getData(String sqlConn, String account, String password, String sql, String[] reNameStr)
throws Exception {
// 1.加载MySql的JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获得数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://"+sqlConn, account, password);
// 3.通过数据库的连接操作数据库,实现增删改查
Statement stmt = conn.createStatement();
// 4.执行sql,并返回结果集,获取到的是行对象
ResultSet rs = stmt.executeQuery(sql);
// 用于存放获取到的列名和值
Map<Object, Object> invoiceMain = new HashMap<Object, Object>();
// 判断是否查询到记录
if (!rs.next()) {
throw new AlertException("未查询到对应的记录");
}
// 将指针置到第一行之前
rs.beforeFirst();
// 获取总列数
int cloumCount = rs.getMetaData().getColumnCount();
// 构造容量为总列数的String数组,存放列名
String[] cloumName = new String[cloumCount];
for (int i = 0; i < cloumCount; i++) {
cloumName[i] = rs.getMetaData().getColumnName(i + 1);// 结果集中的列名指针是从1开始,并非0
System.out.println(rs.getMetaData().getColumnName(i + 1));
}
// 5.取出结果集中需要的字段
while (rs.next()) {
for (int i = 0; i < cloumName.length; i++) {
Object key = reNameStr[i];
Object value = rs.getString(i + 1);
if (key.equals("发票类型")) {
if (value.equals("1")) {
value = "GPO";
} else if (value.equals("3")) {
value = "其他";
}
}
invoiceMain.put(key, value);
}
}
Iterator<Object> itr = invoiceMain.keySet().iterator();
while (itr.hasNext()) {
Object key = itr.next();
Object value = invoiceMain.get(key);
System.out.println("key:" + key + ";value:" + value);
}
return invoiceMain;
}
}