[英]How to get the values from database?
我试图使用Java从数据库中获取值。 输入他的编号时,我需要获取已经保存在数据库中的学生姓名和他的父亲姓名。
我尝试了以下代码,但出现错误。 (在打印堆栈跟踪后编辑错误。)
ClassNotFoundException: oracle.jdbc.driver.OracleDriver
建议解决方案或问题。
import javax.swing.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class Test1 {
JFrame f;
JLabel l1,l2;
JTextField f1;
JButton b1;
Connection con;
Statement st;
ResultSet rs;
/**
* Creates new form Register
*/
public static void main(String args[]) {
Test1 r=new Test1();
r.frame();
r.connect();
}
public void connect() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@//hostname:port/servicename","username","password");
st = (Statement) con.createStatement();
String str = "select student_name,father_name from student_db where roll_no='&roll_no'";
st.executeUpdate(str);
System.out.println(str);
} catch (Exception ex) {
}
}
public void frame()
{
f=new JFrame ("studentrecord");
f1=new JTextField(10);
b1=new JButton("submit");
l1=new JLabel("student_name");
l2=new JLabel("father_name");
f.setLayout(new GridBagLayout());
f.add(l1);
f.add(f1);
f.add(l2);
f.add(b1);
f.setVisible(true);
f.pack();
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String student_name=l1.getText();
String father_name=l2.getText();
String roll_no=f1.getText();
System.out.println(student_name);
System.out.println(father_name);
System.out.println(roll_no);
connect();
}
});
}
}
学生姓名和父亲姓名标签值也应显示在卷号下方,但应显示在提交按钮旁边。是否还有其他更好的布局来显示?
类似于下面的代码将执行读取查询。 但是,为了上帝的缘故,在尝试编写某些东西之前,请先阅读文档。
public String studentName(String rollNo) throws SQLException {
Connection con = null;
PreparedStatement stm = null;
ResultSet rst = null;
String names = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@hostname:port/servicename","username","password");
stm = con.prepareStatement("select student_name,father_name from student_db where roll_no=?");
stm.setString(1, rollNo);
rst = stm.executeQuery();
if (rst.next())
names = rst.getString(1)+","+rst.getString(2);
rst.close();
rst = null;
stm.close();
stm=null;
con.close();
con = null;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (rst!=null) rst.close();
if (stm!=null) stm.close();
if (con!=null) con.close();
}
return names;
}
stm = con.prepareStatement(“从student_db中选择student_name,father_name,其中roll_no =?”); stm.setString(1,rollNo); rst = stm.executeQuery();
这绝对有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.