这里只操作查询示例
数据表结构
CREATE TABLE `test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`pid` int(11) NOT NULL DEFAULT '0',
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
JdbcConnection.java 文件,封闭基本的操作方法
package java_project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JdbcConnection{
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
private void connectionDb() {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
}catch(SQLException e1) {
e1.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public List
示例测试 Hello.java
package java_project;
import java.sql.Types;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Hello{
public static void main(String[] args) {
JdbcConnection jdbcConnection = new JdbcConnection();
String[] columns = new String[] {"2"};
int[] types = new int[] {Types.INTEGER};
String sql = "select * from test where id > ? limit 2";
List> list = jdbcConnection.getResult(sql,columns,types);
System.out.println(list);
for(int i =0; i < list.size();i++) {
Set> map = list.get(i).entrySet();
for(Map.Entry obj : map) {
String key = obj.getKey();
Object val = obj.getValue();
System.out.print(key+":"+val+"\t");
}
System.out.println();
}
}
}