1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statemen... ...
1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6 //雖然是使用的JDBC 但這在里引用的都是sql下的。
7 public class JDBC {
8
9 public static void main(String[] args) {
10 Statement stat = null ;
11 Connection conn=null;
12 ResultSet resultSet= null;
13
14 //1.載入JDBC驅動
15 try {
16 Class.forName("com.mysql.jdbc.Driver");
17 } catch (ClassNotFoundException e) {
18 // TODO Auto-generated catch block
19 e.printStackTrace();
20 }
21 //2、建立資料庫連接
22
23 try {
24 conn= DriverManager.getConnection("jdbc:mysql://localhost:3308/shxt","root","mysql");
25 } catch (SQLException e) {
26 // TODO Auto-generated catch block
27 e.printStackTrace();
28 }
29
30
31 //3、用資料庫連接生成語句對象
32 try {
33 stat= conn.createStatement();
34 } catch (SQLException e) {
35 // TODO Auto-generated catch block
36 e.printStackTrace();
37 }
38 //4、用語句對象執行sql
39 String sqlInsert = "insert into student(sid,sname,age)values(32,'小龍龍',22)";
40 String sqlSelect ="select sid,sname,age from student";
41 int a=0;
42
43 try {
44 resultSet= stat.executeQuery(sqlSelect);
45
46 } catch (SQLException e1) {
47 // TODO Auto-generated catch block
48 e1.printStackTrace();
49 }
50 /*try {
51 int a =stat.executeUpdate(sqlInsert);
52 if(a >0){
53 System.out.println("修改成功!");
54 }else {
55 System.out.println("修改失敗!");
56 }
57 } catch (SQLException e) {
58 // TODO Auto-generated catch block
59 e.printStackTrace();
60 }
61 */
62 try {
63 while(resultSet.next())
64 {
65 String sid = resultSet.getString("sid");
66 String sname = resultSet.getString("sname");
67 String age = resultSet.getString("age");
68 System.out.println(sid+"\t"+sname+"\t"+age);
69 }
70 } catch (SQLException e1) {
71 // TODO Auto-generated catch block
72 e1.printStackTrace();
73 }
74 //5、釋放資源(資料庫連接)
75 try {
76 conn.close();
77 } catch (SQLException e) {
78 // TODO Auto-generated catch block
79 e.printStackTrace();
80 }
81
82 }
83 }