天天看點

mysql連接配接是nio嗎_Java連接配接MySQL資料庫——代碼

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

22 public classSql {23

24

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

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

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 }