Through java database operation, you need to install the relevant dependent package, I am here to operate the mysql database, use the package is: mysql-connector-java version: 5.1.38
You first need to set up the environment, maven repository and find the corresponding package versions:
Address: https://mvnrepository.com/artifact/mysql/mysql-connector-java
Steps:
Build a good environment, followed by the code to operate the database.
Proceed as follows:
Step 3 is to add a placeholder, prevent sql injection, may be skipped.
I have here a method for packaging a universal database query, you can directly take the next change configuration information database, called directly.
code show as below:
Package Comkmgkjawakmavenkday03; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * JDBC database operations * * @author admin * */ public class JDBCDemo { public static void main(String[] args) throws SQLException { JDBCDemo jdbcDemo = new JDBCDemo(); String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false"; String user = "root"; String password = "root"; String sql = "SELECT sname FROM student WHERE age = 23;"; jdbcDemo.query(url, user, password, sql); } /** * 查询方法 * * @param url 数据库的配置信息 * @param user 数据库用户名 * @param password 数据库密码 * @param sql 查询的sql语句 * @throws SQLException */ public void query(String url, String user, String password, String sql) throws SQLException { // 1连接数据库 Connection connection = DriverManager.getConnection(url, user, password); // 2获取PreparedStatement连接对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); // 3调用查询方法,执行查询,返回ResultSet结果集 ResultSet resultSet = preparedStatement.executeQuery(); // 获取查询相关信息 ResultSetMetaData metaData = resultSet.getMetaData(); // 得到查询字段的数目 int columnCount = metaData.getColumnCount(); // 4从结果集中取出查询数据 while (resultSet.next()) { // 循环取出每个查询字段的数据 for (int i = 1; i <= columnCount; i++) { String columnLable = metaData.getColumnLabel(i); String columnValue = resultSet.getObject(columnLable).toString(); System.out.println(columnValue); } } } }