1 packagehadoop.mysql;2
3 importjava.io.IOException;4 importjava.io.InputStream;5 importjava.nio.file.Files;6 importjava.nio.file.Paths;7 importjava.sql.Connection;8 importjava.sql.DriverManager;9 importjava.sql.ResultSet;10 importjava.sql.SQLException;11 importjava.sql.Statement;12 importjava.util.Properties;13
14 /**
15 *16 * @ClassName: Sql17 * @Description: This program tests that the database and the JDBC driver are correctly configured18 *@author***19 * @date 2017-9-4 下午11:27:2220 *21 */
22 public classSql {23
24 /**
25 *26 * @Title: getConnection27 * @Description: Gets a connection from the properties specified in the file database,properties28
29 *@throwsIOException30 *@throwsSQLException31 *@returnConnection32 */
33 public static Connection getConnection ( ) throwsIOException, SQLException34 {35 //创建一个Properties,并加载database.properties
36 Properties props = newProperties() ;37 try ( InputStream in = Files.newInputStream(Paths.get("H://java//com.autwit.www//src//main//resources//database.properties")))38 {39 props.load( in ) ;40 }41 //驱动程序名
42 String drivers = props.getProperty( "jdbc.drivers") ;43 if(drivers != null ) System.setProperty( "jdbc.drivers", drivers ) ;44 //URL指向要访问的数据库名wuwei
45 String url = props.getProperty( "jdbc.url") ;46 //数据库用户名
47 String username = props.getProperty( "jdbc.username") ;48 //密码
49 String password = props.getProperty( "jdbc.password") ;50
51 returnDriverManager.getConnection( url, username, password ) ;52 }53 /**
54 *55 * @Title: runTest56 * @Description: create a connect with MySql,Then executing C(create)R(read)U(Update)D(delete)57 *58 *@throwsSQLException59 *@throwsIOException60 *@returnvoid61 */
62 public static void runTest() throwsSQLException, IOException63 {64 //声明Connection对象
65 try( Connection con =getConnection() )66 {67 //创建statement类对象,用来执行SQL语句
68 Statement stat =con.createStatement( ) ;69 stat.executeUpdate(" create table Greeting ( Message Char(20) )") ;70 stat.executeUpdate( "Insert into Greeting values ('Hello world!' )") ;71 //ResultSet类,用来存放获取的结果集!!
72 try (ResultSet rs = stat.executeQuery("select * from Greeting"))73 {74 /*
75 Notice :即使你十分确定能搜出记录,也不可以在没有rs.next()之前直接对rs进行取值。76 这涉及到rs对象的存储方法。里面说白了就是指针。没next,指针根本没指向对应记录77 */
78 String message = "";79 if(rs.next()){//或者while(rs.next())
80 message = rs.getString("Message");81 if(message == null){82 message = "";83 }84 System.out.println(message);85 }
87 }88 stat.executeUpdate("drop table Greeting") ;
90 }
93 }94
95
96 public static void main(String[] args) throwsSQLException, IOException {97
98 runTest( ) ;99 }
101 }