標籤:指標 ext 資料庫 source ice gets drive stat let
工具:eclipse
MySQL5.7.17
MySQL串連驅動:mysql-connector-java-5.1.43.jar
載入驅動:我是用MAVEN進行管理
資料庫連接資訊:
資料庫名稱:wuwei
資料包名稱:Greeting
連接埠號碼:3306
使用者名稱:root
密碼:******
將這些存放在database.properties檔案中。
原始碼:
1 package hadoop.mysql; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.nio.file.Files; 6 import java.nio.file.Paths; 7 import java.sql.Connection; 8 import java.sql.DriverManager; 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 import java.sql.Statement; 12 import java.util.Properties; 13 14 /** 15 * 16 * @ClassName: Sql 17 * @Description: This program tests that the database and the JDBC driver are correctly configured 18 * @author *** 19 * @date 2017-9-4 下午11:27:22 20 * 21 */ 22 public class Sql { 23 24 /** 25 * 26 * @Title: getConnection 27 * @Description: Gets a connection from the properties specified in the file database,properties 28 29 * @throws IOException 30 * @throws SQLException 31 * @return Connection 32 */ 33 public static Connection getConnection ( ) throws IOException, SQLException 34 { 35 //建立一個Properties,並載入database.properties 36 Properties props = new Properties() ; 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 return DriverManager.getConnection( url, username, password ) ; 52 } 53 /** 54 * 55 * @Title: runTest 56 * @Description: create a connect with MySql,Then executing C(create)R(read)U(Update)D(delete) 57 * 58 * @throws SQLException 59 * @throws IOException 60 * @return void 61 */ 62 public static void runTest() throws SQLException, IOException 63 { 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) throws SQLException, IOException { 97 98 runTest( ) ; 99 }101 }
執行結果:
參考文獻:1,http://www.cnblogs.com/centor/p/6142775.html
2,JAVA核心卷II
Java串連MySQL資料庫——代碼