java数据库的连接与窗体的设计

连接数据库

package test1;
	import java.sql.Connection;
	import java.sql.DriverManager;
	import java.sql.ResultSet;
	import java.sql.SQLException;
	import java.sql.Statement;

public class JdbcConnection {
	//数据库驱动名称
	private static String DRIVER_NAME="com.microsoft.sqlserver.jdbc.SQLServerDriver";
	//数据库连接地址
	private static String DATABASE_URL="jdbc:sqlserver://localhost:1433;DatabaseName=sales";
	//数据库用户名称
	private static String DATABASE_USERNAME="aa";
	//数据库密码
	private static String DATABASE_PASSWORD="123";
	//数据库连接
	private static Connection connection;
	//SQL命令对象
	private static Statement statement;
	//数据查询结果
	private static ResultSet resultSet;
//获取数据库连接
	public static Connection getJdbcConnection() throws SQLException{
		if(connection==null||connection.isClosed()) {
			try {
				//加载驱动程序
				Class.forName(DRIVER_NAME);
				//获取数据库连接
				connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USERNAME, DATABASE_PASSWORD);
			}catch (ClassNotFoundException e ) {
				System.err.println("装在JDBC驱动程序失败。");			
				e.printStackTrace();
			}catch(SQLException e) {
				System.err.println("无法连接数据库");
				e.printStackTrace();
			}
		}
		return connection;
	}
		
	//查询操作
	public static ResultSet executeQuery(String sql) {
		try {
			statement=getJdbcConnection().createStatement();
			resultSet=statement.executeQuery(sql);
		}catch(SQLException e) {
			System.out.println(e);
		}
		return resultSet;
	}
	
	//update 操作
	public static int executeUpdate(String sql) {
		int count=0;//受影响数据行数
		try {
			statement=getJdbcConnection().createStatement();
			count=statement.executeUpdate(sql);
		}catch(SQLException e) {
			System.out.println(e);
		}
		return count;
	}
	
	//关闭数据库
	public static void close() {
		if(resultSet!=null) {
			try {
				resultSet.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		if(statement!=null) {
			try {
				statement.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
		if(connection!=null) {
			try {
				connection.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
	//
	//
	
	
	
	
}



设置窗口

package test1;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
//继承JFrame类
public class JdbcDataView extends JFrame implements ActionListener {
	private static final long serialVersionUID = 1L;
	JMenuBar bar;
	JMenu menuQuery,menuAdd,menuUpdate;
	JMenuItem queryAgents,queryCustomers,queryOrders,queryProducts;
	JMenuItem addAgents,addCustomers,addOrders,addProducts;
	JTextField text;
	JButton button;
	JLabel label;
	JPanel panel;
	JScrollPane jscrollpane;
	JTable table;
	DefaultTableModel dtm;
	ResultSetMetaData rsmd;
	//初始化
	public JdbcDataView() {
		init();///设置窗口位置和大小,前面两个参数分别表示窗口位置的横坐标和纵坐标,后两个参数分别表示窗口大小的宽度和高度
		setBounds(300,100,850,550);
		setVisible(true);//设置可见
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	private void init() {
		setTitle( " JDBC 连接数据库");//设置标题
		setLayout( new BorderLayout( ));//设置布局管理器
		//菜单条和菜单
		bar = new JMenuBar();
		menuQuery =new JMenu("查询");menuAdd = new JMenu("插入");
		bar.add ( menuQuery);//将组件添加到窗口中
		bar.add( menuAdd);
		setJMenuBar(bar);
		//子菜单
		queryAgents = new JMenuItem("查询代理商");
		queryAgents.addActionListener( this);//绑定事件
		menuQuery.add( queryAgents);
		queryCustomers = new JMenuItem("查询客户");
		queryCustomers.addActionListener( this);//绑定事件
		menuQuery.add( queryCustomers);
		queryOrders = new JMenuItem("查询订单");
		queryOrders.addActionListener( this);//绑定事件
		menuQuery.add( queryOrders);
		queryProducts = new JMenuItem("查询商品");
		queryProducts.addActionListener( this);//绑定事件
		menuQuery.add( queryProducts);
		addAgents = new JMenuItem("增加代理商");
		addAgents.addActionListener( this);//绑定事件
		menuAdd.add( addAgents) ;
		addCustomers = new JMenuItem("增加客户");
		addCustomers.addActionListener(this);//绑定事件
		menuAdd.add( addCustomers);
		addOrders = new JMenuItem("增加订单");
		addOrders.addActionListener( this);//绑定事件
		menuAdd.add( addOrders);
		addProducts = new JMenuItem("增加商品");
		addProducts.addActionListener( this);//绑定事件
		menuAdd.add( addProducts);
		//删除数据按钮、输入框
		text = new JTextField( 16);
		button = new JButton("删除");
		label = new JLabel("输人代理商ID删除数据");
		panel = new JPanel();
		panel.add ( label);//将 label控件添加到面板中
		panel.add( text);
		panel.add( button) ;
		button.addActionListener( this);//为按钮注册监听器
		add( panel,BorderLayout.SOUTH);
		JScrollPane scroller = new JScrollPane( table);
		add ( scroller,BorderLayout.CENTER);	
	}

	//触发动作事件时,执行的方法
	public void actionPerformed( ActionEvent e) {
		//如果单击查询代理商按钮
		if ( e.getSource() == queryAgents){
			String sql = " select * from agents" ;
			query(sql);
		}
		//如果单击查询客户按钮
		if( e.getSource() == queryCustomers){
			String sql = "select * from customers";
			query( sql);
		}
		if( e.getSource() == queryOrders){
			String sql = " select * from orders" ;
			query( sql);}
		if( e.getSource( ) == queryProducts){
			String sql = " select * from products" ;
			query( sql);
		}
		if( e.getSource()== addCustomers){
			String sql = " insert into agents values( ' a08', 'test' , 'chongqing' ,8)";
			update( sql );
		}
		if( e.getSource( ) == addOrders){
			String sql = "insert into orders values( '0001','jan'.'cO01’'a08''n01', 2000 ,8)";
			update( sql);
		}
		if( e.getSource() == addOrders) {
			String sql = "insert into orders values('0001' , 'ian''c001’'n08’'n01’.2000,8)";
			update( sql);
		}
		if( e.getSource()== addProducts){
			String sql= " insert into products values( 'p08' , 'test' , ' chongqing’, 1000,1 ) ";
			update( sql);
		}
		if( e.getSource()== button){
			String sql = " delete from agents where aid ='"+text.getText()+"'";
			update( sql);
		}
	}
	
	private void query (String sql){
		ResultSet resultSet = JdbcConnection.executeQuery( sql);//获取数据集
		try {
			displayResultSet (resultSet);
		}catch ( SQLException e1){
			e1.printStackTrace();//在命令行打印异常信息
		}
		JdbcConnection.close();
	}

	private void update( String sql){
		int count = JdbcConnection.executeUpdate( sql);//
		System.out.println("受影响行数:"+count );
		JdbcConnection.close();
	}
	
	@SuppressWarnings({ "unchecked" , "rawtypes" })//用于抑制编译器产生警告信息
	private void displayResultSet ( ResultSet rs) throws SQLException {
		Vector colum = new Vector( );
		Vector rows = new Vector( );
		try {
			rsmd = rs.getMetaData();//获取数据集属性名
			for ( int i= 1; i<= rsmd.getColumnCount(); ++i)
				colum.addElement( rsmd.getColumnName(i));
			while ( rs.next() ){
				Vector currow = new Vector();
				for ( int i = 1; i<= rsmd.getColumnCount();++i){
					currow.addElement( rs.getString(i));
				}
				rows.addElement( currow );
			}
			table = new JTable( rows, colum) ;
			add ( table,BorderLayout.CENTER);
			table.setVisible(true);
			table.setRowHeight(50);
		}catch ( SQLException e1){
			e1.printStackTrace();
		}
		JScrollPane scroller = new JScrollPane( table);
		Container c = getContentPane();
		c.remove(1);
		c.add( scroller,BorderLayout.CENTER);
		//刷新Table
		c.validate();
	}
	
	public static void main(String[] args) {
		JdbcDataView jdbcDataView = new JdbcDataView();
	}
}





  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我可以为您提供一些代码示例,帮助您开始编写Java资产管理系统窗体连接MySQL数据库。 首先,您需要下载并安装MySQL数据库,然后创建一个名为“asset_management”的数据库。在该数据库中,您需要创建一个名为“assets”的表,其中包含以下列:id(INT,主键,自动增加),name(VARCHAR),description(VARCHAR),value(DOUBLE)和acquisition_date(DATE)。 接下来,您需要使用Java连接到MySQL数据库。这可以通过使用Java JDBC驱动程序来实现。以下是一个示例代码: ```java import java.sql.*; public class MySQLConnector { private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost/asset_management"; private static final String USER = "your_username"; private static final String PASS = "your_password"; public static Connection getConnection() { Connection conn = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (Exception e) { e.printStackTrace(); } return conn; } } ``` 这个类使用了静态方法`getConnection()`来连接到MySQL数据库。您需要将`your_username`和`your_password`分别替换为您的MySQL用户名和密码。 接下来,您可以编写一个Java类来表示资产,并使用该类在Java窗体中显示和管理资产。以下是一个示例代码: ```java import java.util.Date; public class Asset { private int id; private String name; private String description; private double value; private Date acquisitionDate; public Asset(int id, String name, String description, double value, Date acquisitionDate) { this.id = id; this.name = name; this.description = description; this.value = value; this.acquisitionDate = acquisitionDate; } public int getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public double getValue() { return value; } public Date getAcquisitionDate() { return acquisitionDate; } } ``` 这个类表示一个资产,并包含`id`,`name`,`description`,`value`和`acquisitionDate`属性。您可以使用这个类来在Java窗体中显示和管理资产。 最后,您需要编写Java窗体以显示和管理资产。以下是一个示例代码: ```java import java.sql.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Date; public class AssetManagementSystem extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; private static final String[] COLUMNS = {"ID", "Name", "Description", "Value", "Acquisition Date"}; private static final String[] FIELD_NAMES = {"Name", "Description", "Value", "Acquisition Date (YYYY-MM-DD)"}; private JTextField[] fields; private JButton addButton; private JTable table; private DefaultTableModel model; private ArrayList<Asset> assets; public AssetManagementSystem() { super("Asset Management System"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // Create fields for asset details JPanel fieldPanel = new JPanel(new GridLayout(FIELD_NAMES.length, 2)); fields = new JTextField[FIELD_NAMES.length]; for (int i = 0; i < FIELD_NAMES.length; i++) { fieldPanel.add(new JLabel(FIELD_NAMES[i])); fields[i] = new JTextField(); fieldPanel.add(fields[i]); } add(fieldPanel, BorderLayout.NORTH); // Create add button addButton = new JButton("Add Asset"); addButton.addActionListener(this); add(addButton, BorderLayout.SOUTH); // Create table to display assets model = new DefaultTableModel(COLUMNS, 0); table = new JTable(model); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); // Load assets from database assets = new ArrayList<>(); try { Connection conn = MySQLConnector.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM assets"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String description = rs.getString("description"); double value = rs.getDouble("value"); Date acquisitionDate = rs.getDate("acquisition_date"); Asset asset = new Asset(id, name, description, value, acquisitionDate); assets.add(asset); model.addRow(new Object[] {id, name, description, value, acquisitionDate}); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } // Configure window setSize(800, 600); setVisible(true); } public static void main(String[] args) { new AssetManagementSystem(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == addButton) { try { Connection conn = MySQLConnector.getConnection(); PreparedStatement stmt = conn.prepareStatement("INSERT INTO assets (name, description, value, acquisition_date) VALUES (?, ?, ?, ?)"); stmt.setString(1, fields[0].getText()); stmt.setString(2, fields[1].getText()); stmt.setDouble(3, Double.parseDouble(fields[2].getText())); stmt.setDate(4, Date.valueOf(fields[3].getText())); stmt.executeUpdate(); stmt.close(); conn.close(); Asset asset = new Asset(assets.size() + 1, fields[0].getText(), fields[1].getText(), Double.parseDouble(fields[2].getText()), Date.valueOf(fields[3].getText())); assets.add(asset); model.addRow(new Object[] {asset.getId(), asset.getName(), asset.getDescription(), asset.getValue(), asset.getAcquisitionDate()}); for (JTextField field : fields) { field.setText(""); } } catch (Exception ex) { ex.printStackTrace(); } } } } ``` 这个窗体使用`Asset`类表示资产,并在窗体中显示和管理资产。窗体包括一个表格来显示资产,一个文本框来输入新资产的详细信息,以及一个“添加资产”按钮来将新资产添加到数据库和表格中。 当用户单击“添加资产”按钮时,窗体连接到MySQL数据库并将新资产添加到数据库和表格中。如果发生任何错误,窗体将打印出堆栈跟踪以帮助您调试代码。 希望这个示例代码可以帮助您开始编写Java资产管理系统窗体连接MySQL数据库

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值