java的jdbc数据库操作,现在我要的是查询数据。求一个完整的代码。要从连接数据库开始,已知有一
2014-06-24
敲个例子给你参考一下
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class JDBCTest extends JFrame implements ActionListener {
private Connection conn;
private JTextField textField;
private JButton button;
private JTextArea textArea;
private PreparedStatement ps;
private ResultSet rs;
public JDBCTest() {
super("查询");
textField = new JTextField("输入查询的姓名");
textArea = new JTextArea();
button = new JButton("查询");
button.addActionListener(this);
this.add(textField, BorderLayout.NORTH);
this.add(textArea);
this.add(button, BorderLayout.SOUTH);
this.setSize(350, 200);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(3);
this.setVisible(true);
}
public Connection getConnection() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager
.getConnection("jdbc:oracle:thin:@127.1:1521:orcl", "scott", "tiger");
return conn;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void actionPerformed(ActionEvent e) {
textArea.setText(null);
try {
ps = getConnection()
.prepareStatement("select * from mytable where 姓名 = ?");
ps.setString(1, textField.getText().trim());
rs = ps.executeQuery();
if (rs.next()) {
textArea.append("姓名:" + rs.getObject(1) + "\t年龄:" + rs
.getObject(2) + "\t性别:" + rs.getObject(3));
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
new JDBCTest();
}
}
效果图:
这个你可以随便写
就比如表school.字段name和sex
mysql
mysql有两种方式,JDBC连接和ODBC-JDBC桥连接
由于太长就不在这赘述了,给你个链接
http://jingyan.baidu.com/article/0aa2237599b89888cc0d64c0.html
很详细,两种方式都有。不过个人感觉ODBC-JDBC桥要简单一点