statement.executeQuery) not working in NetBeans java - 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.

Related

No suitable driver found for jdbc:mysql//localhost/sakila

I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";

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;
}
}

executeQuery ERROR for JDBC

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();

How to insert data into database from the main file?

I've got 2 file in my java project : MysqlConnect and Main .
I want to run query from Main class.It's possible?
This is MysqlConnect file:
public class MysqlConnect {
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public Statement stmt;
public String query = "";
public int rs;
public void crearedatabase() {
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
// System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
And this is the Main file:
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
The error(Exception) is on the MysqConnection at the try/catch
rs = stmt.executeUpdate(query);
You assign statement object to a local variable named stmt instead of the object field with the same name.
Replace this
Statement stmt = conn.createStatement();
With this:
this.stmt = conn.createStatement();
this is not necessary here, but it's a good practice to have it there.

simple data comparison with MySQL, nullpointerexception

I'm currently being thrown into the depths by my school and they are expecting me to program a simple login form using sql. They have given us brief examples on how they use JDBC and what it all is, but haven't really explained step by step how to use it on our own. Therefore i have snatched a bit of code from an example but i'm unable to get it working. I keep receiving an nullpointerexception and i can't figure out why :(
Here's the connection class:
package Database;
import java.sql.*;
public class MySQLConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost/corendon";
public static final String DBUSER = "root";
public static final String DBPASS = "simplepass";
private ResultSet result = null;
private int affectedRows = -1;
Connection conn = null;
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
}
}
public void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (Exception e) {
}
conn = null;
}
public ResultSet performSelect(PreparedStatement prdstmt) throws SQLException {
result = prdstmt.executeQuery();
return result;
}
public int performUpdate(PreparedStatement prdstmt) throws SQLException {
affectedRows = prdstmt.executeUpdate();
return affectedRows;
}
public Connection getConnection() {
return conn;
}
}
And here is the method i'm getting the exception in (in a different class):
MySQLConnection conn = new MySQLConnection();
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
prdstmt = conn.getConnection().prepareStatement(query);
prdstmt.setInt(1, id);
prdstmt.setString(2, pass);
rs = conn.performSelect(prdstmt);
while (rs.next()){
String tempPass = rs.getString("password");
int tempId = rs.getInt("id");
}
if(conn != null){
conn.closeConnection();
}
}
I'm getting the nullpointerexception on line:
prdstmt = conn.getConnection().prepareStatement(query);
Why does it throw an exception there, but not when i start the connection and also how do i solve this? Thanks in advance.
When you call startConnection(), you are throwing an Exception
public void startConnection() {
try {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (Exception e) {
//An exception occurs here, but you don't do anything about it
}
}
Therefore, when you call getConnection(), the conn variable is still null, which is throwing the NullPointerException.
Either make startConnection() throw an exception so that you're forced to deal with it (this is usually how most JDBC drivers work anyway), or check to see if the conn variable is null before you start using it.
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
conn.startConnection();
if (conn.getConnection() == null) {
throw new SQLException("Connection is null!");
}
Or (what I think would personally be better)
public void startConnection() throws Exception {
Class.forName(DRIVER);
DriverManager.setLoginTimeout(5);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
}
public void compareData(int id, String pass) throws SQLException{
ResultSet rs = null;
PreparedStatement prdstmt = null;
String query = "SELECT id, password FROM users WHERE id=?, password=?";
try {
conn.startConnection();
} catch (Exception e) {
throw new SQLException(e);
}
Also as a tip, you should probably avoid declaring your classes as the same name of other classes you are using. This is all happening in your own MySQLConnection class, but that could be confusing with the actual com.mysql.jdbc.MySQLConnection class.

Categories