这是我的高级项目。请记住,我还是初学者。
所以我想创建一个搜索应用,用户将选择一个专业'从JComboBox开始,一旦他们点击“搜索”,该应用程序将从MySQL数据库中检索数据并将其显示在JTable中。
由于我不是编程方面的专家,所以我遵循了一些教程,并且我坚持这个错误:
未知专栏'架构'在' where子句'
'建筑'是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);
}
}
});
答案 0 :(得分:1)
更好的解决方案是使用PreparedStatement
- 如果您的某个专业是Being "cool"
,即使它包含引号字符,您也不会遇到麻烦。
Prepared语句还可以保护您免受SQL注入攻击。
PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM mydb.applications WHERE speciality LIKE ?");
ps.setString(1, specialty);
ResultSet rs = ps.executeQuery();
答案 1 :(得分:0)
尝试在输入周围添加引号:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE '" + speciality + "'");
答案 2 :(得分:0)
这里的问题在于您的SQL查询语法:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE " + speciality);
应该是:
rows = st.executeQuery("SELECT * FROM mydb.applications WHERE speciality LIKE '" + speciality+"'");