1 package org.warnier.zhang.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.ResultSetMetaData; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 public class MySQLTest { 11 12 /** 13 * @param args 14 * @throws ClassNotFoundException 15 * @throws SQLException 16 */ 17 public static void main(String[] args) throws ClassNotFoundException, 18 SQLException { 19 // 加载驱动程序;(虚拟机加载类,而非在编程的过程中要使用这个类。) 20 Class.forName("com.mysql.jdbc.Driver"); 21 22 // 建立数据库连接; 23 Connection connection = DriverManager 24 .getConnection("jdbc:mysql://localhost/userinfo", "warrior", "[email protected]"); 25 26 // 创建SQL语句,执行语句,返回结果集; 27 Statement statement = connection.createStatement(); 28 ResultSet resultSet = statement.executeQuery("SELECT * FROM User"); 29 30 // 处理结果集(包括元数据); 31 // 打印属性名; 32 ResultSetMetaData rsMetaData = resultSet.getMetaData(); 33 for (int i = 1; i <= rsMetaData.getColumnCount(); i++) { 34 System.out.printf("%-8s\t", rsMetaData.getColumnName(i)); 35 } 36 System.out.println(); 37 38 // 打印属性值; 39 while (resultSet.next()) { 40 for (int i = 1; i <= rsMetaData.getColumnCount(); i++) { 41 System.out.printf("%-12s\t", resultSet.getString(i)); 42 } 43 System.out.println(); 44 } 45 46 // 关闭数据库连接;(连接数据库在Java应用程序中是笔很大的开销。) 47 connection.close(); 48 } 49 50 }
时间: 2024-10-09 23:03:09