當前位置:編程學習大全網 - 源碼下載 - 如何使用eclipse調用數據庫中的內容,並將數據顯示出來?具體步驟和代碼··

如何使用eclipse調用數據庫中的內容,並將數據顯示出來?具體步驟和代碼··

我用的數據庫是mysql,下載這個東東mysql-connector-java-5.1.15.zip解壓把mysql-connector-java-5.1.15-bin.jar導入到妳要連接數據庫的項目中(應該知道怎麽導入吧!)然後就是代碼,以下代碼是插入數據庫的例子

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

import java.sql.*;

public class Login2 {

private Connection connection;

private JButton button1;

private JFrame frame;

private JLabel nameLabel,pwdLabel;

private JTextField nameTA,pwdTA;

private JPanel panel;

// private Statement stat;

private ResultSet rs;

public Login2()

{

String url = "jdbc:mysql://localhost:3306/(此處填寫妳創建的數據庫名字)";

String username = "(此處填寫妳的數據庫用戶,例如root)";

String password = "(此處填寫妳的數據庫安裝時設置的密碼)";

//加載驅動程序以連接數據庫

try {

Class.forName( "org.gjt.mm.mysql.Driver" );

connection = DriverManager.getConnection(

url, username, password );

}

//捕獲加載驅動程序異常

catch ( ClassNotFoundException cnfex ) {

System.err.println(

"裝載 JDBC/ODBC 驅動程序失敗。" );

cnfex.printStackTrace();

System.exit( 1 ); // terminate program

}

//捕獲連接數據庫異常

catch ( SQLException sqlex ) {

System.err.println( "無法連接數據庫" );

sqlex.printStackTrace();

System.exit( 1 ); // terminate program

}

frame = new JFrame();

panel = new JPanel();

panel.setLayout(new GridLayout(3,2));

nameLabel = new JLabel("user");

pwdLabel = new JLabel("password");

nameTA = new JTextField();

pwdTA = new JTextField();

button1 = new JButton("insert");

button1.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

String str1 = nameTA.getText();

String str2 = pwdTA.getText();

String str = "insert into user values('"+str1+"','"+str2+"')";

try {

// Statement stat = null;

PreparedStatement pstmt = connection.prepareStatement(str);

pstmt.executeUpdate();

} catch (SQLException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

JOptionPane.showMessageDialog(null, "yes");

}

});

panel.add(nameLabel);

panel.add(nameTA);

panel.add(pwdLabel);

panel.add(pwdTA);

panel.add(button1);

frame.add(panel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300,100);

frame.setVisible(true);

}

/**

* @param args

*/

public static void main(String[] args) {

Login2 l = new Login2();

}

}

還有問題可以繼續聯系

  • 上一篇:建站用ASP好還是PHP好點,本人對ASP比較熟,雖然也不專,有專業人士請指點下謝謝!
  • 下一篇:股票報價c源代碼
  • copyright 2024編程學習大全網