java.sql.SQLException : Illegal operation on empty result set - java

I have code like this
String sql_kode_kategori = "select kategori from data_kategori \n" +
"where kode_kategori = ?";
try{
pst = (PreparedStatement) koneksiMySQL.GetConnection().prepareStatement(sql_kode_kategori);
pst.setString(1, (String)cbKategori.getSelectedItem());
rst2 = pst.executeQuery();
rst2.next();
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
javax.swing.JOptionPane.showMessageDialog(null, "Data CES Berhasil Ditambahkan");
ClearField();
TampilTabel();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
i tried to get kode_kategori with kategori but that error appear, please help me

If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as
if(rst2.next()) {
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
} else {
// handle invalid category
}

Remove \n from your query:
String sql_kode_kategori = "select kategori from data_kategori where kode_kategori = ?";
Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.

Related

Retrieve sum from database

try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost;databaseName=QLLTCK;integratedSecurity=true;";
Connection connection = DriverManager.getConnection(url);
String sql = "SELECT SUM(soSV) AS sumSoSV FROM PHANCONG WHERE tenMH = 'Công nghệ phần mềm chuyên sâu'";
PreparedStatement pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()){
int SumSoSV = rs.getInt("sumSoSV");
JOptionPane.showMessageDialog(null,"Số sinh viên dự thi: " + SumSoSV);
}
}
catch(Exception sqlex){
JOptionPane.showMessageDialog(null, sqlex);
}
I cannot retrieve the sum of soSV from my PHANCONG table. Its result is 0. When I tried to use String instead of int, its result is null.
Can someone help me? Thanks.
Image
I guess you need to add N before string literal to handle unicode characters:
String sql = "SELECT SUM(soSV) AS sumSoSV FROM PHANCONG WHERE tenMH = N'Công nghệ phần mềm chuyên sâu'"

I have written this code for fetch record from my table name is owners... but some error is occurs... is there something missing?

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystationary", "root", "");
Statement stmt = con.createStatement();
String qry;
qry = "select * from owners where usernm='" + jTextField1.getText() + "',password='" + jTextField2.getText() + "'";
ResultSet rs = stmt.executeQuery(qry);
while (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
} catch (HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
You have to use PreparedStatement instead to avoid any syntax error or SQL Injection:
try (PreparedStatement ps = con.prepareStatement(
"select * from owners where usernm = ? and password = ?")) {
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
ResultSet rs = ps.executeQuery(qry);
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
}
Your real problem is with the , when you want to use where you have to use and not ,
qry = "select * from owners where usernm='"+jTextField1.getText()+"', password='"+jTextField2.getText()+"'";
//------------------------------------------------------------------^
Instead you have to use :
qry = "select * from owners where usernm='"+jTextField1.getText()+"' and password='"+jTextField2.getText()+"'";
//-------------------------------------------------------------------^^^
But PreparedStatement is more secure.
Another thing, if you want to check for one use, then you can use if (rs.next()) instead of while (rs.next())
On this line:
qry = "select * from owners where usernm='"+jTextField1.getText()+"',password='"+jTextField2.getText()+"'";
You are using a comma to separate your conditions when you should be using the SQL operator "AND."
qry = "SELECT * FROM owners WHERE usernm='"+jTextField1.getText()+"' AND password='"+jTextField2.getText()+"'";
Also, as Dave Newton pointed out, this code is vulnerable to SQL injection. And your while loop after the executeQuery() call doesn't actually use your result set.

Don't know how to convert to string and print ResultSet, SELECT statement

This is a small piece of my code. Basically, i do not know how to print my ResultSet or turn it into string.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state = con.createStatement();
String query = "SELECT description FROM topics WHERE title = '" + title + "'";
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results = state.executeQuery(query);
// selects * of the rows from "comment" table where the topic equals the selected title.
ResultSet results2 = state.executeQuery(query2);
desc = results.toString();
}
You can not convert ResultSet to string neither you can print directly from ResultSet.
Following code may help you.
try {
String url = "jdbc:odbc:" + "userstuff";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"","");
// Gets a statement
Statement state1 = con.createStatement();
Statement state2 = con.createStatement();
String query1 = "SELECT description FROM topics WHERE title = '" + title + "'";
// selects the description for the selected topic ( title will be referenced to the chosen topic)
ResultSet results1 = state1.executeQuery( query1 );
while( results.next() ){
System.out.println( results1.getString( "description" );
}
// selects * of the rows from "comment" table where the topic equals the selected title.
String query2 = "SELECT * FROM comment WHERE topic = '" + title + "'";
ResultSet results2 = state2.executeQuery( query2 );
while( results2.next() ){
System.out.println( results2.getString( 1 ); // here 1 is tables 1st column
System.out.println( results2.getString( 2 ); // here 2 is tables 2nd column
}
} Exception( SQL e){
e.printStackTrace();
}

Java SQLite Select Query

I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again

How to get a particular column's values alone?

I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}

Categories