环境:
OS: centos 602
IDE ; eclipse + jdk 1.6-33
驱动:mysql-connector-java-5.0.8.tar.gz地址:http://dev.mysql.com/downloads/connector/j/5.0.html
代码 :
package test1; import java.sql.*; public class Mytest { public static void main(String[] args) { // TODO Auto-generated method stub Connection connection = null; String url = "jdbc:mysql://192.168.10.10:3306/testdb"; String username = "test"; String password = "passwd"; //加载驱动程序以连接数据库 try { Class.forName( "com.mysql.jdbc.Driver" ); connection = DriverManager.getConnection( url, username, password ); } //捕获加载驱动程序异常 catch ( ClassNotFoundException cnfex ) { System.err.println( "装载 JDBC/ODBC 驱动程序失败。" ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } //捕获连接数据库异常 catch ( SQLException sqlex ) { System.err.println( "无法连接数据库" ); sqlex.printStackTrace(); System.exit( 1 ); // terminate program } Statement stat = null; ResultSet rs = null; // 要执行的SQL语句 String sql = "select * from obc_ad"; try { stat = connection.createStatement(); rs = stat.executeQuery(sql); String name = null; while (rs.next()) { // 选择sname这列数据 name = rs.getString("ad_name"); System.out.println(name); // 输出结果 } rs.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }