【Java/MySql】使用JDBC访问MySql数据库的Maven工程
下载链接:https://files.cnblogs.com/files/xiandedanteng/FindNotnullColumns20191102-1.rar
pom.xml里写:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hy</groupId> <artifactId>FindNotnullColumns</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
代码:
package com.hy; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; import org.apache.log4j.Logger; public class Test { private static Logger log = Logger.getLogger(Test.class); private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://192.168.161.129:3306/test"; private static final String USER = "root"; private static final String PSWD = "12345678"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName(JDBC_DRIVER).newInstance(); conn = DriverManager.getConnection(DB_URL, USER, PSWD); stmt = conn.createStatement(); String sql = "select id,name,age,cdate from emp order by id limit 10"; ResultSet rs = stmt.executeQuery(sql); int index = 0; while (rs.next()) { index++; String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String cdate = rs.getString("cdate"); String raw = "#{0},{1},{2},{3},{4}"; Object[] arr = { index, id, name, age, cdate }; String outStr = MessageFormat.format(raw, arr); log.info(outStr); } } catch (Exception e) { System.out.print("DB/SQL ERROR:" + e.getMessage()); } finally { try { stmt.close(); conn.close(); } catch (SQLException e) { System.out.print("Can't close stmt/conn because of " + e.getMessage()); } } } }
输出:
INFO [main] - #1,8035200,E:8035200,0,2018-02-02 00:00:00.0 INFO [main] - #2,8035201,E:8035201,1,2018-02-02 00:00:01.0 INFO [main] - #3,8035202,E:8035202,2,2018-02-02 00:00:02.0 INFO [main] - #4,8035203,E:8035203,3,2018-02-02 00:00:03.0 INFO [main] - #5,8035204,E:8035204,4,2018-02-02 00:00:04.0 INFO [main] - #6,8035205,E:8035205,5,2018-02-02 00:00:05.0 INFO [main] - #7,8035206,E:8035206,6,2018-02-02 00:00:06.0 INFO [main] - #8,8035207,E:8035207,7,2018-02-02 00:00:07.0 INFO [main] - #9,8035208,E:8035208,8,2018-02-02 00:00:08.0 INFO [main] - #10,8035209,E:8035209,9,2018-02-02 00:00:09.0
--END-- 2019年11月2日08:12:09