package com.hy.action; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Analysis { public static void main(String args[]) { Connection con = null; try { // 获得MySQL驱动的实例 Class.forName("com.mysql.jdbc.Driver").newInstance(); // 提供地址用户名密码并获得连接对象 con = DriverManager.getConnection("jdbc:mysql://192.168.1.113/h","root", "root"); if (!con.isClosed()) // 连接成功提示 System.out.println("Successfully connected to MySQL server using TCP/IP..."); // 有Connection对象创建Statement Statement st = con.createStatement(); // 运行SQL语句读取 ResultSet rs = st.executeQuery("SELECT * FROM Ption"); // 循环读取数据 while (rs.next()) { // 打印数据 System.out.println(rs.getString("ID")); } // 关闭 con.close(); } catch(Exception e) { System.err.println("Exception: " + e.getMessage()); } } }
注,如果有子查询的,就不用用Statement
String sql = "SELECT SysVersion FROM P_ClientInformation where ID =(select max(ID) from P_ClientInformation)"; PreparedStatement pst = con.prepareStatement(sql); ResultSet rs2 = pst.executeQuery(); // 循环读取数据 while (rs2.next()) { // 取出数据库最新版本号