怎么样将数据库的表在Java中界面中显示出来

Python013

怎么样将数据库的表在Java中界面中显示出来,第1张

这里的表是指JTable吗?

是的话

这里有个运行通过的程序:

import javax.swing.*

import javax.swing.table.JTableHeader

import java.awt.event.ActionEvent

import java.awt.event.ActionListener

import java.sql.*

public class Test extends JFrame{

// 定义组件

private JScrollPane scpDemo

private JTableHeader jth

private JTable tabDemo

private JButton btnShow

// 构造方法

public Test(){

// 窗体的相关属性的定义

super("JTable数据绑定示例")

this.setSize(330,400)

this.setLayout(null)

this.setLocation(100,50)

// 创建组件

this.scpDemo = new JScrollPane()

this.scpDemo.setBounds(10,50,300,270)

this.btnShow = new JButton("显示数据")

this.btnShow.setBounds(10,10,300,30)

// 给按钮注册监听

this.btnShow.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

btnShow_ActionPerformed(ae)

}

})

// 将组件加入到窗体中

add(this.scpDemo)

add(this.btnShow)

// 显示窗体

this.setVisible(true)

}

// 点击按钮时的事件处理

public void btnShow_ActionPerformed(ActionEvent ae){

// 以下是连接数据源和显示数据的具体处理方法,请注意下

try{

// 获得连接

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

Connection conn = DriverManager.getConnection("jdbc:odbc:localServer","sa","")

// 建立查询条件

String sql = "select * from localServer"

PreparedStatement pstm = conn.prepareStatement(sql)

// 执行查询

ResultSet rs = pstm.executeQuery()

// 计算有多少条记录

int count = 0

while(rs.next()){

count++

}

rs = pstm.executeQuery()

// 将查询获得的记录数据,转换成适合生成JTable的数据形式

Object[][] info = new Object[count][4]

count = 0

while(rs.next()){

info[count][0] = Integer.valueOf( rs.getInt("id"))

info[count][1] = rs.getString("name")

info[count][2] = Integer.valueOf( rs.getInt("age") )

info[count][3] = rs.getString("sex")

count++

}

// 定义表头

String[] title = {"学号","姓名","年龄","性别"}

// 创建JTable

this.tabDemo = new JTable(info,title)

// 显示表头

this.jth = this.tabDemo.getTableHeader()

// 将JTable加入到带滚动条的面板中

this.scpDemo.getViewport().add(tabDemo)

}catch(ClassNotFoundException cnfe){

JOptionPane.showMessageDialog(null,"数据源错误","错误",JOptionPane.ERROR_MESSAGE)

}catch(SQLException sqle){

JOptionPane.showMessageDialog(null,"数据操作错误","错误",JOptionPane.ERROR_MESSAGE)

}

}

public static void main(String[] args){

new Test()

}

}

链接数据库代码最好封装成一个类,不然到处都写的是连接数据库的代码,用数据源链接数据库,代码如下:package Designer.FamilyAccountMoney.commimport java.io.IOException

import java.io.InputStream

import java.sql.Connection

import java.sql.PreparedStatement

import java.sql.ResultSet

import java.sql.SQLException

import java.util.HashMap

import java.util.Propertiesimport javax.sql.DataSourceimport org.apache.commons.dbcp.BasicDataSourceimport Designer.FamilyAccountMoney.main.exception.ExceptionDemopublic class DBUtil {

private static final String driver

private static final String url

private static final String username

private static final String password

private static DataSource datasource

private static HashMap<String,String>mapstatic {

Properties config = new Properties()

InputStream in = DBUtil.class.getResourceAsStream("config.properties")

try {

config.load(in)

} catch (IOException e) {

throw new ExceptionDemo("装载配置文件出错",e)

}

driver = config.getProperty("jdbc.driver")

url = config.getProperty("jdbc.url")

username = config.getProperty("jdbc.username")

password = config.getProperty("jdbc.password")

map = new HashMap<String, String>()

map.put("login.selectbynamepassword",config.getProperty("sql.login.selectbynamepassword"))

map.put("login.selectbyname",config.getProperty("sql.login.selectbyname"))

map.put("login.insert",config.getProperty("sql.login.insert"))

map.put("accountmoney.insert",config.getProperty("sql.accountmoney.insert"))

map.put("accountmoney.selectall",config.getProperty("sql.accountmoney.selectall"))

map.put("accountmoney.delete",config.getProperty("sql.accountmoney.delete"))

map.put("accountmoney.selectByDate",config.getProperty("sql.accountmoney.selectByDate"))

map.put("salary.selectall",config.getProperty("sql.salary.selectall"))

map.put("salary.selectbyname",config.getProperty("sql.salary.selectbyname"))

map.put("salary.delete",config.getProperty("sql.salary.delete"))

map.put("salary.insert",config.getProperty("sql.salary.insert"))

map.put("sort.selectall",config.getProperty("sql.sort.selectall"))

map.put("sort.selectbyname",config.getProperty("sql.sort.selectbyname"))

map.put("sort.delete",config.getProperty("sql.sort.delete"))

map.put("sort.insert",config.getProperty("sql.sort.insert"))

} public static DataSource getConnection() {

if(datasource==null){

BasicDataSource bds

bds = new BasicDataSource()

bds.setDriverClassName(driver)

bds.setUrl(url)

bds.setUsername(username)

bds.setPassword(password)

datasource = bds

}

return datasource}

public static HashMap<String,String>getMap() {

return map

} // 释放资源

public static void realse(ResultSet rst, PreparedStatement psd, Connection conn) {

try {

if (rst != null) {

rst.close()

}

} catch (SQLException e) {

e.printStackTrace()

} finally {

try {

if (psd != null)

psd.close()

} catch (SQLException e) {

e.printStackTrace()

} finally {

try {

if (conn != null)

conn.close()

} catch (SQLException e) {

e.printStackTrace()

}

}

}

}

}

用法:例如判断用户名和密码:public static boolean Justice(String username, String password) {

try {

conn = dbs.getConnection()

psd = conn

.prepareStatement(map.get("login.selectbynamepassword"))

psd.setString(1, username)

psd.setString(2, password)

rst = psd.executeQuery()

flag = rst.next()

} catch (SQLException e) {

throw new ExceptionDemo("判断用户名和密码时出错", e)

} finally {

DBUtil.realse(rst, psd, conn)

}

if (flag) {

return true

}

return false

} 不过我给你的这个链接数据库要有配置文件,即:。property的文件:如下:jdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver

jdbc.url=jdbc:odbc:driver={Microsoft Access Driver (*.mdb)}DBQ=stud.mdb

jdbc.username=

jdbc.password=

sql.login.selectbynamepassword=select user_name,pass_word from login where user_name=? and pass_word=?

sql.login.selectbyname=select username from login where username=?

sql.login.insert=insert into login(username,sex,age,user_name,pass_word) values(?,?,?,?,?) sql.accountmoney.insert=insert into account_money(in_out,sort_in_out,date_money,money_account,ps) values(?,?,?,?,?)

sql.accountmoney.selectall=select id,in_out,sort_in_out,date_money,money_account,ps from account_money

sql.accountmoney.selectByDate=select id,in_out,sort_in_out,date_money,money_account,ps from account_money where date_money between ? and ?

sql.accountmoney.delete=delete from account_money where id=?

sql.salary.selectall=select * from salary

sql.salary.selectbyname=select * from salary where in_sort=?

sql.salary.delete=delete from salary where in_sort=?

sql.salary.insert=insert into salary(in_sort) values(?)sql.sort.selectall=select * from sort

sql.sort.selectbyname=select * from sort where out_sort=?

sql.sort.delete=delete from sort where out_sort=?

sql.sort.insert=insert into sort(out_sort) values(?)不是很难,应该看的懂,上半部分是链接数据库必备条件,下面是执行的sql语句,在Dbutil里用静态代码快读出来。。这个是最底层的链接方式。。还有其他的第三方类库链接数据库。如:hibanate等等。。

使用JDBC进行数据库的增删改查操作1.下载Microsoft SQL Server 2005 JDBC 驱动包jar文件 将jar文件引入工程中2.封装数据库链接的获取和关闭操作import java.sql.*public class BaseDao {\x0d\x0a /**\x0d\x0a * 数据库驱动类的字符串,完整的包名加类名 在工程中查看添加的jar文件 能看到这个类\x0d\x0a */\x0d\x0a private static final String DRIVE = "com.microsoft.sqlserver.jdbc.SQLServerDriver"/**\x0d\x0a * 数据库连接地址\x0d\x0a * \x0d\x0a * DataBaseName=数据库名称 其它固定\x0d\x0a */\x0d\x0a private static final String URL = "jdbc:sqlserver://localhost:1433DataBaseName=bbs"/**\x0d\x0a * 连接数据库的用户名\x0d\x0a */\x0d\x0a private static final String USER = "sa"/**\x0d\x0a * 用户密码\x0d\x0a */\x0d\x0a private static final String PASSWORD = ""/**\x0d\x0a * 获取连接 异常直接抛出 或者捕获后自定义异常信息再抛出\x0d\x0a */\x0d\x0a public static Connection getConnection() throws Exception {\x0d\x0a Class.forName(DRIVE)\x0d\x0a return DriverManager.getConnection(URL, USER, PASSWORD)\x0d\x0a } /**\x0d\x0a * 关闭与数据库的连接 释放资源\x0d\x0a */\x0d\x0a public static void closeAll(ResultSet resultSet, PreparedStatement pst,\x0d\x0a Connection connection) throws Exception {\x0d\x0a if (resultSet != null)\x0d\x0a resultSet.close()\x0d\x0a if (pst != null)\x0d\x0a pst.close()\x0d\x0a if (connection != null)\x0d\x0a connection.close()\x0d\x0a }}3.创建图书的实体类public class Book {\x0d\x0a /**\x0d\x0a * 数据库主键\x0d\x0a */\x0d\x0a private Long id/**\x0d\x0a * 作者\x0d\x0a */\x0d\x0a private String author/**\x0d\x0a * 书名\x0d\x0a */\x0d\x0a private String name\x0d\x0a /**\x0d\x0a * 默认构造\x0d\x0a *\x0d\x0a */\x0d\x0a public Book() {\x0d\x0a }\x0d\x0a /**\x0d\x0a * 全字段构造\x0d\x0a * @param id\x0d\x0a * @param author\x0d\x0a * @param name\x0d\x0a */\x0d\x0a public Book(Long id, String author, String name) {\x0d\x0a this.id = id\x0d\x0a this.author = author\x0d\x0a this.name = name\x0d\x0a }\x0d\x0a /**\x0d\x0a * 以下为读写属性的方法\x0d\x0a * @return\x0d\x0a */\x0d\x0a public String getAuthor() {\x0d\x0a return author\x0d\x0a }\x0d\x0a public void setAuthor(String author) {\x0d\x0a this.author = author\x0d\x0a }\x0d\x0a public Long getId() {\x0d\x0a return id\x0d\x0a }\x0d\x0a public void setId(Long id) {\x0d\x0a this.id = id\x0d\x0a }\x0d\x0a public String getName() {\x0d\x0a return name\x0d\x0a }\x0d\x0a public void setName(String name) {\x0d\x0a this.name = name\x0d\x0a }\x0d\x0a}\x0d\x0a4.创建与图书表交互的工具类import java.sql.Connection\x0d\x0aimport java.sql.PreparedStatement\x0d\x0aimport java.sql.ResultSet\x0d\x0aimport java.util.ArrayList\x0d\x0aimport java.util.Listpublic class BookDao {\x0d\x0a /**\x0d\x0a * 添加新书\x0d\x0a * \x0d\x0a * @param book 要添加入数据库的图书 作者 书名 必须给定\x0d\x0a */\x0d\x0a public void addBook(Book book) throws Exception {\x0d\x0a // 连接\x0d\x0a Connection connection = null\x0d\x0a // 执行语句\x0d\x0a PreparedStatement pst = null\x0d\x0a try {\x0d\x0a connection = BaseDao.getConnection()\x0d\x0a // 构造执行语句\x0d\x0a String sql = "insert into book values(" + book.getAuthor() + ","\x0d\x0a + book.getName() + ")"\x0d\x0a pst = connection.prepareStatement(sql)\x0d\x0a pst.executeUpdate() } catch (Exception e) {\x0d\x0a // 抛出异常\x0d\x0a throw e\x0d\x0a } finally {\x0d\x0a // 无论是否异常 均关闭数据库\x0d\x0a BaseDao.closeAll(null, pst, connection)\x0d\x0a }\x0d\x0a } /**\x0d\x0a * 查询所有书籍列表\x0d\x0a */\x0d\x0a public List getBooks() throws Exception {\x0d\x0a // 用于存放查寻结果的集合\x0d\x0a List books = new ArrayList()\x0d\x0a // 连接\x0d\x0a Connection connection = null\x0d\x0a // 执行语句\x0d\x0a PreparedStatement pst = null\x0d\x0a // 查询结果\x0d\x0a ResultSet resultSet = null\x0d\x0a try {\x0d\x0a connection = BaseDao.getConnection()\x0d\x0a // 构造查询语句\x0d\x0a String sql = "select * from book"\x0d\x0a pst = connection.prepareStatement(sql)\x0d\x0a resultSet = pst.executeQuery() // 循环读取查询结果行\x0d\x0a while (resultSet.next()) {\x0d\x0a// getXXX的参数为数据表列名\x0d\x0aBook book = new Book(resultSet.getLong("id"), resultSet\x0d\x0a .getString("author"), resultSet.getString("name"))\x0d\x0a// 将封装好的图书对象存入集合\x0d\x0abooks.add(book)\x0d\x0a }\x0d\x0a } catch (Exception e) {\x0d\x0a // 抛出异常\x0d\x0a throw e\x0d\x0a } finally {\x0d\x0a // 无论是否异常 均关闭数据库\x0d\x0a BaseDao.closeAll(resultSet, pst, connection)\x0d\x0a }\x0d\x0a // 返回查询结果\x0d\x0a return books\x0d\x0a }/***其它方法类似上面 只是语句不同*/\x0d\x0a}当然 以上只是简单的封装 初学者可以在理解以上代码的基础上 进行更高级的封装\x0d\x0a5.使用BookDao添加书籍和获取所有书籍列表import java.util.List/**\x0d\x0a * 测试类\x0d\x0a * @author Administrator\x0d\x0a *\x0d\x0a */\x0d\x0apublic class Test { /**\x0d\x0a * @param args\x0d\x0a * @throws Exception \x0d\x0a */\x0d\x0a public static void main(String[] args) throws Exception {\x0d\x0a //创建工具类对象\x0d\x0a BookDao dao = new BookDao()\x0d\x0a //创建一本图书\x0d\x0a Book book = new Book(null,"QQ:495691293","编程菜鸟")\x0d\x0a //添加书籍到数据库\x0d\x0a dao.addBook(book)\x0d\x0a \x0d\x0a //获取所有图书列表\x0d\x0a List books = dao.getBooks()\x0d\x0a //输出结果\x0d\x0a for (Book b : books) {\x0d\x0a System.out.println(b.getId()+"\t"+b.getAuthor()+"\t"+b.getName())\x0d\x0a }\x0d\x0a }}