这是我的高级项目。请记住我还是个初学者。
因此,我想创建一个搜索应用程序,用户将从jcombobox中选择一个“专业”,一旦他们单击“搜索”,该应用程序将从mysql数据库检索数据并在jtable中显示。
因为我不擅长编程,所以我遵循了一些教程,我被这个错误困住了:
“where子句”中的未知列“architecture”
“架构”是jcombobox中的选项之一,但我认为sql将它作为一列来读取,尽管它是一行!
我的问题是:
public class MyQuery {
public Connection getConnection(){
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata?autoReconnect=true&useSSL=false", "root", "1110");
} catch (SQLException ex) {
Logger.getLogger(Query.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public ArrayList<Applications> getData(String speciality){
ArrayList<Applications> list = new ArrayList<Applications>();
Connection con = getConnection();
Statement st;
ResultSet rows;
try {
st = con.createStatement();
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE " + speciality);
Applications applications;
while(rows.next()){
applications = new Applications(
rows.getInt("id"),
rows.getString("name"),
rows.getString("nationality"),
rows.getString("speciality"),
rows.getString("experience")
);
list.add(applications);
}
} catch (SQLException ex) {
Logger.getLogger(MyQuery.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}
&
JButton btnSearch = new JButton("Search...\n");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MyQuery mq = new MyQuery();
ArrayList<Applications> list = mq.getData((String)comboBox_searchSp.getSelectedItem());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"ID","Name","Nationality","Speciality","Experience"});
Object[] row = new Object[5];
for(int i = 0; i < list.size(); i++){
row[0] = list.get(i).getName();
row[1] = list.get(i).getNationality();
row[2] = list.get(i).getSpeciality();
row[3] = list.get(i).getExperience();
model.addRow(row);
}
table.setModel(model);
}
public void BindCombo(){
MyQuery mq = new MyQuery();
Connection con = mq.getConnection();
Statement st;
ResultSet rows;
try {
st = con.createStatement();
rows = st.executeQuery("SELECT `id`, `name` FROM mydb.applications");
while(rows.next()){
comboBox_searchSp.addItem(rows.getInt(1));
}
} catch (SQLException ex) {
Logger.getLogger(AdminPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
3条答案
按热度按时间h9vpoimq1#
更好的解决方法是使用
PreparedStatement
--如果你的特长是Being "cool"
,即使它包含引号字符。准备好的语句还可以保护您免受sql注入攻击。
nbnkbykc2#
试着用引号括住输入:
c6ubokkw3#
这里的问题在于sql查询语法:
应该是: