本文實(shí)例講述了java基于jdbc連接數(shù)據(jù)庫及顯示數(shù)據(jù)操作。分享給大家供大家參考,具體如下:
1. 導(dǎo)入jdbc包
java要連接mysql數(shù)據(jù)庫需要用到j(luò)dbc工具(mysql-connector-java-5.1.39-bin.jar),這是一個(gè)jar包,不同的數(shù)據(jù)庫對(duì)應(yīng)不同的jar包,這里用的是mysql數(shù)據(jù)庫jar包,導(dǎo)入很簡單,鼠標(biāo)對(duì)項(xiàng)目右擊 - build path - configure build path - 右側(cè)選libraries - add external jars,選擇正確的jdbc包就行了。
2. 創(chuàng)建數(shù)據(jù)庫(示例: 數(shù)據(jù)庫名studentdb , 表名stable)
3. 新建屬性及構(gòu)造方法類(stuinfo.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
public class stuinfo { private int sno; private string sname; private string sex; private int age; public int getsno() { return sno; } public void setsno( int sno) { this .sno = sno; } public string getsname() { return sname; } public void setsname(string sname) { this .sname = sname; } public string getsex() { return sex; } public void setsex(string sex) { this .sex = sex; } public int getage() { return age; } public void setage( int age) { this .age = age; } public stuinfo(){ } public stuinfo( int sno, string sname, string sex, int age) { this .sno = sno; this .sname = sname; this .sex = sex; this .age = age; } } |
3. 新建主類(shoetest.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import info.stuinfo; import java.util.arraylist; import java.sql.*; public class showtest { public static void main(string[] args) { arraylist<stuinfo> list = getallstus(); if (list.size() == 0 ){ system.out.println( "暫無數(shù)據(jù)" ); } else { for (stuinfo s: list){ //遍歷集合數(shù)據(jù) system.out.println(s.getsno()+ "\t" +s.getsname()+ "\t" +s.getsex()+ "\t" +s.getage()); } } } //采用集合的方法,返回?cái)?shù)據(jù)集合 public static arraylist<stuinfo> getallstus(){ arraylist<stuinfo> stulist = new arraylist<stuinfo>(); string url = "com.mysql.jdbc.driver" ; //加載驅(qū)動(dòng)包 string connectsql = "jdbc:mysql://127.0.0.1:3306/studentdb" ; //鏈接mysql數(shù)據(jù)庫 string sqluser = "root" ; //數(shù)據(jù)庫賬號(hào) string sqlpasswd = "*****" ; //你的數(shù)據(jù)庫密碼 connection con = null ; preparedstatement psm = null ; resultset rs = null ; try { //加載驅(qū)動(dòng)包 class .forname(url); //連接mysql con = drivermanager.getconnection(connectsql,sqluser,sqlpasswd); //執(zhí)行mysql語句 psm = con.preparestatement( "select * from stable" ); rs = psm.executequery(); system.out.println( "編號(hào)" + "\t" + "姓名" + "\t" + "性別" + "\t" + "年齡" ); while (rs.next()){ stuinfo s = new stuinfo(); s.setsno(rs.getint( 1 )); s.setsname(rs.getstring( 2 )); s.setsex(rs.getstring( 3 )); s.setage(rs.getint( 4 )); stulist.add(s); } //關(guān)閉數(shù)據(jù)庫連接 rs.close(); psm.close(); con.close(); } catch (exception e) { system.out.println( "顯示所有數(shù)據(jù)報(bào)錯(cuò),原因:" +e.getmessage()); } return stulist; } } |
4. 運(yùn)行測(cè)試
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/chauncywu/article/details/54773760