1、首先我們先建好資料庫,然後建立好程序的目錄,因為是適用於初學者的,所以就建立一個簡單的java project,如圖。
Ⅱ java 連接資料庫代碼 jdbc
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class QueryFrame extends JFrame implements ActionListener{
JTextField jf = new JTextField(20);
String[] value = {"姓名","部門","薪水"};
JComboBox box = new JComboBox(value);
JButton find = new JButton("查詢");
JPanel panel_find = new JPanel();
JPanel panel_content = new JPanel();
Statement stmt = null;
public QueryFrame() {
this.setTitle("查詢系統");
Container c = this.getContentPane();
//完成查找界面的設置
jf.addActionListener(this);
find.addActionListener(this);
panel_find.add(jf);
panel_find.add(box);
panel_find.add(find);
c.add(panel_find,"North");
c.add(panel_content,"Center");
this.setSize(400,400);
this.setLocation(200,100);
//連接SQL Server資料庫
stry{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://192.168.56.102:1433;databasename=yzhdb","sa","123");
stmt = conn.createStatement();
}catch(Exception e){
e.printStackTrace();
}
this.setVisible(true);
}
public void actionPerformed(ActionEvent e){
panel_content.removeAll();
String item = (String)box.getSelectedItem();
//確定用戶所選擇的查詢依據
if(item.equals("姓名")){
item = "name";
}
if(item.equals("部門")){
item = "department";
}
if(item.equals("薪水")){
item = "salary";
}
//獲取用戶輸入的查詢關鍵字
String content = jf.getText();
int i = 0;
try{
String sql = "select * from employee";
if(!content.equals("")){
sql = sql +" where "+item+" like '%"+content+"%'";
}
//執行查詢語句,並顯示查詢結果
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String department = rs.getString(3);
int salary = rs.getInt(4);
JLabel label = new JLabel(id + " " + name + " " + department + " " + salary);
JPanel panel = new JPanel();
panel.add(label);
panel_content.add(panel);
i++;
}
}catch(Exception e1){
e1.printStackTrace();
}
panel_content.setLayout(new GridLayout(i,1));
panel_content.validate();
}
public static void main(String[] args) {
(new QueryFrame()).setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
以上是一個實例。
你的錯誤代碼是什麼???