本文实例讲述了java基于jdbc连接数据库及显示数据操作。分享给大家供大家参考,具体如下:
1. 导入jdbc包
java要连接mysql数据库需要用到jdbc工具(mysql-connector-java-5.1.39-bin.jar),这是一个jar包,不同的数据库对应不同的jar包,这里用的是mysql数据库jar包,导入很简单,鼠标对项目右击 - build path - configure build path - 右侧选libraries - add external jars,选择正确的jdbc包就行了。
2. 创建数据库(示例: 数据库名studentdb , 表名stable)
3. 新建属性及构造方法类(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( "暂无数据" ); } else { for (stuinfo s: list){ //遍历集合数据 system.out.println(s.getsno()+ "\t" +s.getsname()+ "\t" +s.getsex()+ "\t" +s.getage()); } } } //采用集合的方法,返回数据集合 public static arraylist<stuinfo> getallstus(){ arraylist<stuinfo> stulist = new arraylist<stuinfo>(); string url = "com.mysql.jdbc.driver" ; //加载驱动包 string connectsql = "jdbc:mysql://127.0.0.1:3306/studentdb" ; //链接mysql数据库 string sqluser = "root" ; //数据库账号 string sqlpasswd = "*****" ; //你的数据库密码 connection con = null ; preparedstatement psm = null ; resultset rs = null ; try { //加载驱动包 class .forname(url); //连接mysql con = drivermanager.getconnection(connectsql,sqluser,sqlpasswd); //执行mysql语句 psm = con.preparestatement( "select * from stable" ); rs = psm.executequery(); system.out.println( "编号" + "\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); } //关闭数据库连接 rs.close(); psm.close(); con.close(); } catch (exception e) { system.out.println( "显示所有数据报错,原因:" +e.getmessage()); } return stulist; } } |
4. 运行测试
希望本文所述对大家java程序设计有所帮助。
原文链接:https://blog.csdn.net/chauncywu/article/details/54773760