java jdbc

时间:2019-06-12
本文章向大家介绍java jdbc,主要包括java jdbc使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

 


public class Myframe extends JFrame {

private JPanel contentPane;
private JTextField textField;
private JComboBox comboBox;
private JButton btnNewButton;
ArrayList <Goods> goodlist;
double price[];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Myframe frame = new Myframe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Myframe() throws Exception {
setTitle("\u4EA7\u54C1\u67E5\u8BE2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(3, 1, 0, 0));

JPanel panel = new JPanel();
contentPane.add(panel);

JLabel lblNewLabel = new JLabel("\u4EA7\u54C1\u540D\uFF1A");
panel.add(lblNewLabel);

comboBox = new JComboBox();
panel.add(comboBox);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","");
Statement stat = conn.createStatement();
ResultSet rest = stat.executeQuery("select * from fruit");
goodlist = new ArrayList<Goods>();
while(rest.next()){
String n = rest.getString(1);
double p = rest.getDouble(2);
Goods g = new Goods(n,p);
goodlist.add(g);
}
rest.close();
stat.close();
conn.close();
int length = goodlist.size();
price=new double[length];
Goods g;
for(int i=0;i<length;i++){
g=goodlist.get(i);
comboBox.addItem(g.getName());
price[i]=g.getPrice();
}


JPanel panel_1 = new JPanel();
contentPane.add(panel_1);

JLabel lblNewLabel_1 = new JLabel("\u4EF7\u683C\uFF1A");
panel_1.add(lblNewLabel_1);




textField = new JTextField();
panel_1.add(textField);
textField.setColumns(10);

JPanel panel_2 = new JPanel();
contentPane.add(panel_2);

btnNewButton = new JButton("\u67E5\u8BE2");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int index=comboBox.getSelectedIndex();
textField.setText(price[index]+"");
}
});
panel_2.add(btnNewButton);
}
}

$flag 上一页 下一页