executeQuery ERROR for JDBC - java

Hi I'm new to JDBC and ran into executeQuery error while constructing the JDBC. I just want to display all the information in the student table. I used the prepareStatement and I didn't set any parameter since I don't have. It works when use createStatement.
This is the error I'm getting
The method executeQuery(String) in the type Statement is not applicable for the arguments ()
How can I get it working using prepareStatement.
public class Test3 extends JFrame{
Vector rowData,columnNames;
JTable jt = null;
JScrollPane jsp = null;
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
//constructor
public Test3() {
columnNames = new Vector();
rowData = new Vector();
columnNames.add("Student_ID");
columnNames.add("Name");
columnNames.add("Gender");
columnNames.add("Age");
columnNames.add("DOB");
columnNames.add("Major");
try {
//1. Get a connection to database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stu?useSSL=false","root","1972");
//2. Create a prepareStatement
myStmt = myConn.prepareStatement("Select * from student");
// 3. Set the parameters
// no need to set the parameters, because there is not parameter needed to be set
// 4. Execute SQL query
***myRs = myStmt.executeQuery();***
while(myRs.next()) {
Vector col = new Vector();
col.add(myRs.getString(1));
col.add(myRs.getString(2));
col.add(myRs.getString(3));
col.add(myRs.getInt(4));
col.add(myRs.getString(5));
col.add(myRs.getString(6));
rowData.add(col);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(myRs!=null) myRs.close();
if(myStmt!=null) myStmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test3 test3 = new Test3();
}
}

You used the wrong method. For Statement, the definition of executeQuery is
ResultSet executeQuery(String sql) throws SQLException;
For PreparedStatement, the difinition is ResultSet executeQuery() throws SQLException;
So you can either use PreparedStatement myStmt = null; or myRs = ((PreparedStatement )myStmt).executeQuery();

Related

statement.executeQuery) not working in NetBeans java

I am trying to output the first column (nameID) of my table (StudentInfo) in my database. But the statement.executeQuery is not working and ResultSet.next() is false.
Java NetBeans program
Calls sqlite database
Uses "jdbc:sqlite:ProjectWeekDB.sqlite" as url
private static Connection connection = null;
private static PreparedStatement stmt = null;
private static Statement statement = null;
private static ResultSet results = null;
public static void createNewDatabase() {
String sqlData = "SELECT * FROM StudentInfo";
String url;
try {
connection = DriverManager.getConnection(url);
if (connection != null) {
statement = connection.createStatement();
stmt = connection.prepareStatement(sqlData);
statement.executeUpdate(sqlData);
results = statement.executeQuery(sqlData);
while (results.next()) {
print(results.getInt("nameID"));
}
stmt.close();
results.close();
}
} catch (SQLException e) {
print(e.getMessage());
}
}
public static void main(String[] args) {
createNewDatabase();
}
It just prints out BUILD successful without actually displaying the first column in the database.

Ambiguous behavior of ResultSet

I have a requirement to create separate POJO which will set/get sql ResultSet and use its methods throughout my project code like below. I have created below 2 classes
public class Tester3
{
public MyResultSet test() throws SQLException{
MyResultSet mrs = new MyResultSet();
PreparedStatement ps = null;
String values = null;
boolean flag = false;
String one = "'12'";
String two = "'jt'";
String a = null;
String b = null;
try {
if(flag==true)
{
values = "'3%'";
a =null;
b = "OR id IN(\'" +a+ "\')";
}else
{
values = "'%'";
a = one + "," + two;
b = "AND id IN("+a+")";
}
String sql = "SELECT * FROM veracodetable where orts like PARAM RAMAN";
sql = sql.replaceFirst("PARAM", values);
sql = sql.replaceFirst("RAMAN", b);
System.out.println("SQL: "+sql);
ps = new Connection1().getConnection().prepareStatement(sql);
ps.executeQuery();
mrs.setRs(ps.executeQuery());
System.out.println("ResultSet: "+mrs.getRs().next());
} catch (SQLException e) {
e.printStackTrace();
}
return mrs;
}
public static void main(String[] args) throws SQLException {
Tester3 t = new Tester3();
MyResultSet rs = t.test();
System.out.println("ResultSet: "+rs.getRs().next());
}
}
public class MyResultSet {
ResultSet rs = null;
public ResultSet getRs() {
return rs;
}
public void setRs(ResultSet rs) {
this.rs = rs;
}
}
When executed above code with separate POJO MyResultSet, I don't get any result in ResultSet. However if I skip POJO implementation and use resultSet directly, I am able to get results.
Is rs.getRs() invoking at all? If not, why?
I would separate the statements as they dont't perform the same function, and then populate;
PreparedStatemet ps = null;
ResultSet rs = null;
if(flag){
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}else{
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}
}

use one jdbc connection class for all classes java

i have been using this JDBC conection in all of my class that had to run query but i created a new class which i dont want the constructor with a parameter of the DConnection from JDBC Class(main Database Class).
but i keep on getting NullPointExceptions. Can anyway figur out what that problem may be.
Thanks.
public class UsersDao {
// associating the Database Connection objekt
private DConnector connector;
private final Connection myConn;
// Constructor
public UsersDao() throws CZeitExceptionHand,SQLException {
myConn = connector.getConnenction();
}
public boolean updateUsers(String mitarb, int mid) throws SQLException{
// PreparedStatement myStmt = null;
Statement stmt = myConn.createStatement();
try {
String myStmt = "SELECT Bly "
+ "" + mid + ";";
return stmt.execute(myStmt);
} finally {
close(stmt);
}
}
Example like this Method which is working but in different class
String[][] getAllTheWorkers(DConnector connector) throws CZeitExceptionHand {
try {
Connection connect = connector.getConnenction();
Statement stmt = connect.createStatement();
ResultSet result = stmt.executeQuery("SELECT ");
result.last();
int nt = result.getRow();
result.beforeFirst();
}
return results;
} catch (SQLException e) {
throw new CZeitExceptionHand("Error: " + e);
}
}
The object does not seem to be initialized.
Can you please post which method is not working and from where it is invoked ?
P.S : Unable to add a comment - that is why have answered !

SQLite connection w/ Libgdx .Desktop

Well, I'm trying to use SQLite in my Libgdx game, but don't know how.
public class Main {
public static void main(String[] args){
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = Game.TITLE;
config.width = Game.V_WIDTH * Game.SCALE;
config.height = Game.V_HEIGHT * Game.SCALE;
new LwjglApplication(new Game(), config);
}}
What I need to do in my main? lol
I've been looking for this but, all I can find is related to Android application.
I already have the driver in my ref libraries, and connection class..
What I usually do when using a database with an application, is make a ConnectionFactory, that returns a new connection to the database.
public class ConnectionFactory {
public static Connection getConnection() {
Connection con = null;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:test.db"); //change to whatever db you want
return con;
}
}
now we have a ConnectionFactory that can pump out connections to our database. Now when we want to interact with the database, you can get the connection appropriately. inside your main, it might look something like this:
public static void main(String[] args) {
Connection con = null;
String firstName = null, lastName = null;
try {
con = ConnectionFactory.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM myTable where myId = ?");
pstmt.setInt(1, /*some id here, ill put this as example:*/ 1234567);
//execute the query and put into result set so we can get the values.
ResultSet rs = pstmt.executeQuery();
//the resultset iterates through rows, by calling next
if( rs.next() ) //could be while(rs.next()) if expecting multiple rows
{
firstName = rs.getString("firstName"); //column name you want to grab here
lastName = rs.getString("lastName");
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally {
try {
con.close(); //dont forget to close your connection to database!
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
}
You will need to create tables within the SQLite database and insert records before you can do any interactions though, so keep that in mind.

How to update column values in the table?

What is the problem in this code? where it is update the all column values with the same last one .
public class dbconnection {
java.sql.Connection con;
java.sql.Statement st;
ResultSet rs;
public EncBean getConnection()throws SQLException{
EncBean encBean1 = new EncBean();
String v_url= "jdbc:oracle:thin:#192.168.2.138:1522:orcl2";
String v_username= "scott";
String v_password = "tiger";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(v_url,v_username,v_password);
System.out.println ("Connection to Oracle database was Established");
}
catch ( SQLException e)
{
e.printStackTrace();
}
return encBean1;
}
public EncBean selectRows()
{
EncBean encBean2 = new EncBean();
try
{
String SQLselect="select JOB_NAME from job";
st=con.createStatement();
rs=st.executeQuery(SQLselect);
while (rs.next()) {
encBean2.setName(rs.getString("JOB_NAME"));
}
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return encBean2;
}
public void updateRows(String updatedname){
try
{
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
ResultSet srs = stmt.executeQuery("select job_name from job " );
while (srs.next()) {
srs.updateString("job_name", updatedname);
srs.updateRow();
con.commit();}
System.out.println("An existing user was updated successfully!");}
catch(SQLException err){
System.out.println(err.getMessage());
}}}
This is the main
public class mainenc {
public static void main(String[] args) throws Exception{
dbconnection dbcon = new dbconnection();
EncBean encbeancon= dbcon.getConnection();
EncBean encBean5 = dbcon.selectRows();
enc concatinputs = new enc();
EncBean encBeanconcat = concatinputs.funconcat(encBean5.getName());
EncBean encBean4 = concatinputs.inputencryption(encBeanconcat.getConcatenatedData());
String vReserverbin= encBean4.getReversedBinary();
String ascistring= concatinputs.convertBinaryStringToString(vReserverbin);
dbcon.updateRows(ascistring);
}}
What is the problem in this code? where it is update the all column values with the same last one .
After updated method you should write list method again.
Try to take this example:
UPDATE tableB
SET tableB.value , tableA.value, tableB.value)
WHERE tableA.name = 'Joe'
It is kind of obvious: dbcon.updateRows(...) calls for the update method and that method does the job.
But as Erhan said, you don't get to see the result because you don't actually make use of updated records, e.g. show them etc. At least, you can check it out at the DB level if op is completed.
But I really disliked your comment:
plz can you do it for me?
You should do your own task and ask help when you need a hand. But never expect someone else to do your job mate.

Categories