導航:首頁 > 編程大全 > java登錄鏈接資料庫代碼

java登錄鏈接資料庫代碼

發布時間:2025-03-16 22:35:06

Ⅰ 怎麼使用java連接資料庫

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);
}
}
以上是一個實例。

你的錯誤代碼是什麼???

閱讀全文

與java登錄鏈接資料庫代碼相關的資料

熱點內容
網路中常用的傳輸介質 瀏覽:518
文件如何使用 瀏覽:322
同步推密碼找回 瀏覽:865
樂高怎麼才能用電腦編程序 瀏覽:65
本機qq文件為什麼找不到 瀏覽:264
安卓qq空間免升級 瀏覽:490
linux如何刪除模塊驅動程序 瀏覽:193
at89c51c程序 瀏覽:329
怎麼創建word大綱文件 瀏覽:622
裊裊朗誦文件生成器 瀏覽:626
1054件文件是多少gb 瀏覽:371
高州禁養區內能養豬多少頭的文件 瀏覽:927
win8ico文件 瀏覽:949
仁和數控怎麼編程 瀏覽:381
項目文件夾圖片 瀏覽:87
怎麼在東芝電視安裝app 瀏覽:954
plc顯示數字怎麼編程 瀏覽:439
如何辨別假網站 瀏覽:711
寬頻用別人的賬號密碼 瀏覽:556
新app如何佔有市場 瀏覽:42

友情鏈接