demo structure:
JDBC database connection:
jdbc database is connected to the most basic embodiment of the connection data, the need to introduce a jar mysql-connection
Creates a normal java project, create a folder lib introduction jar package, added to the striking can directly connect to the database
code show as below:
package conn;
import java.sql.*;
public class JdbcCon {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
/**
* jdbc连接数据库,分为五个步骤如下:
*/
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jtsys", "root", "root");
//3.获取传输器
Statement statement = connection.createStatement();
String sql = "select * from sys_users";
//4.处理结果
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
String username = resultSet.getString("username");
String mobile = resultSet.getString("mobile");
String email = resultSet.getString("email");
System.out.println("username="+username+";mobile="+mobile+";email="+email);
}
//5.关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
Now many of the framework are to be jdbc package, and the result set processing package, encapsulated framework has brought us great convenience, but as an entry-white, hoping to slowly strengthen its start with the basics.
Here is the result set himself to create objects for processing:
user table structure
First: Create a user object, the object has been simplified
package pojo;
public class User {
private Integer id;
private String username;
private String mobile;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", mobile='" + mobile + '\'' +
", email='" + email + '\'' +
'}';
}
}
Second: Create JdbcUtil
package utils;
import java.sql.*;
public class JdbcUtil {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jtsys","root","root");
return connection;
}
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
}
}
Third: the test object map
package conn;
import pojo.User;
import utils.JdbcUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JdbcConPojo {
public static void main(String[] args) {
/**
* 对结果集进行处理,主要依赖反射,通过对象的set方法给对象赋值
* 为了方便起见,将jdbc的获取连接和关闭资源的方法封装到工具类中
*/
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtil.getConnection();
statement = connection.createStatement();
String sql = "select id,username,mobile,email from sys_users";
resultSet = statement.executeQuery(sql);
//根据结果集获取列数据
String[] columnDatas = getColumnData(resultSet);
//获取对象的所有方法
Method[] methods = User.class.getMethods();
//创建user数组列表封装数据
List<User> userList = new ArrayList<User>();
while (resultSet.next()){
for (int i = 0; i <columnDatas.length ; i++) {
//获取对象实例
User user = User.class.newInstance();
//获取列名
String columnName = columnDatas[i];
//构建set方法
String methodName = "set"+columnName;
//遍历所有方法,构建方法和对象方法匹配时,注入值
for (Method method : methods) {
if(methodName.equalsIgnoreCase(method.getName())){
method.invoke(user,resultSet.getObject(columnName));
break;
}
}
userList.add(user);
}
}
for (User user : userList) {
//sout在项目中是被日志所替代的,这里为了学习没有引入log包
System.out.println(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}finally {
JdbcUtil.close(connection,statement,resultSet);
}
}
private static String[] getColumnData(ResultSet resultSet) throws SQLException {
//获取元数据
ResultSetMetaData metaData = resultSet.getMetaData();
//获取总列数
int columnCount = metaData.getColumnCount();
//遍历并添加到数组中
String[] columns = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columns[i-1] = metaData.getColumnLabel(i);
}
return columns;
}
}
jdbc database in connection with the actual work is substantially less than that too cumbersome and troublesome operation, involving the need to write code for a long time operation of multiple databases.
Here is an insert delete modify demo:
package conn;
import utils.JdbcUtil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class JdbcMethod {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
//ResultSet resultSet = null;
try {
connection = JdbcUtil.getConnection();
statement = connection.createStatement();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String updateSql = "update sys_users set username='chengcheng' where id='19'";
String deleteSql = "delete from sys_users where id='19'";
String insertSql =
"insert into sys_users values(19,'wangcheng','12345','12345','[email protected]','18889996666',1,2,'"+dateFormat.format(new Date())+"','"+dateFormat.format(new Date())+"','admin','admin')";
/*boolean insertFlag = statement.execute(insertSql);
System.out.println(insertFlag);*/
boolean updateFlag = statement.execute(updateSql);
System.out.println(updateFlag);
System.out.println("输入D删除数据,请输入:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
if(s.equalsIgnoreCase("d")){
boolean deleteFlag = statement.execute(deleteSql);
System.out.println(deleteFlag);
}
System.out.println("删除成功,需要重新插入数据请输入I,请输入:");
String i = scanner.nextLine();
if(i.equalsIgnoreCase("i")){
boolean insertFlag = statement.execute(insertSql);
System.out.println(insertFlag);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.close(connection,statement,null);
}
}
}
Here learning jdbc connection to the database is over, after this record forgot easier to find. There is something wrong, correct me hope big brother, very grateful! ! !