天天看点

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 }