So I'm just really new with the whole database getting connected to Java and for my project i decided to integrate some gui since it's seems to make things easier and user friendly. For some reason, I can't add values because I'm getting asked where the VALUES keyword is even though it's there. Can someone help? really lost here :(
try{
//get connection
DBconnection dbconn = new DBconnection();
dbconn.login("homeuser", "12345");
dbconn.connect();
con =dbconn.getConnection();
//insert values
Statement statement = con.createStatement();
String sql =("INSERT INTO StudentInfo"+
"VALUES('first_name,'last_name,'StudID)");
statement.executeUpdate(sql);
JOptionPane.showConfirmDialog(rootPane, "Record Added.");
con.commit();
first.setText("");
last.setText("");
idText.setText("");
}catch(SQLException sqlex){
System.out.println(sqlex.getErrorCode()+" "+sqlex.getMessage());
}
You are missing a space. added after StudentInfo. check now.
//insert values
Statement statement = con.createStatement();
String sql =("INSERT INTO StudentInfo "+
"VALUES('first_name’,'last_name’,'StudID’)");
statement.executeUpdate(sql);
Related
I am trying to obtain records from my MySQL database that I am not hosting. My code will not produce any results or throw any errors. I am just getting an empty results set even though there are definitely records that exist in the database. In fact, when I write my statement in console, it returns the data. I'm not sure why it isn't working in the code.
What I've tried:
I tested my SQL query statement in console to double check it is correct. The statement works in console, so I don't think this is it.
My SQL connection should be working because I use the same connection method in another part of the code where I am inserting records into the database and it works there. I do close the connection I create there as soon as the method I am getting results from is complete to avoid concurrent connections.
I tried stopping the console connection to make sure the issue wasn't from concurrent connections. I don't think it is, because I completely deleted the data source out of my console and I was still running into the issue. Plus, even when the database exists in my console, I can still add records without running into any issues.
For more info, I am coding this on Intellij Idea. My console is also Intellij's database console. The database is a MySQL database that I do not host on my machine.
OLD CODE, NEW CODE HAS BEEN UPDATED PER COMMENTS (ISSUE STILL ONGOING)
public ObservableList loadUsers(){
Connection conn;
PreparedStatement stmt;
ResultSet rs;
//userList is a global var in this class declared at the top
userList = FXCollections.observableArrayList();
try {
conn = Model.SQL_Connection.connect();
System.out.println(conn);
String resultString = "select userID, userName, lastUpdate, lastUpdatedBy from user";
stmt = conn.prepareStatement(resultString);
rs = stmt.executeQuery();
//used this to check size of resultset
//it always returns 0
System.out.println(rs.getFetchSize());
//for each row
while(rs.next()){
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
//for each column
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
row.add(rs.getString(i));
}
userList.add(row);
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
//convert results if needed
//put results into table
return userList;
}
NEW CODE:
public ObservableList loadUsers(){
//call result set
Connection conn;
PreparedStatement stmt;
ResultSet rs;
userList = FXCollections.observableArrayList();
try {
conn = Model.SQL_Connection.connect();
System.out.println(conn);
String resultString = "select userID, userName, lastUpdate, lastUpdatedBy from user";
stmt = conn.prepareStatement(resultString);
rs = stmt.executeQuery();
//for each row
while(rs.next()){
//Iterate Row
ObservableList<String> row = FXCollections.observableArrayList();
//for each column
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
row.add(rs.getString(i));
}
userList.add(row);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
//convert results if needed
//put results into table
return userList;
}
Results from code above are that the connection was successful, not throwing any errors, and that the rs.getFetchSize() is 0. I think this is the right method to use to test but this is my first SQL project so I could be wrong.
If someone knows what I could do to return actual results, I would greatly appreciate it. I've spent quite a few hours looking around, but maybe it's something simple that someone with more experience will be able to spot. I will follow up here if I find a solution.
Recently I'm just learning some HTML, JSP and servlets for a university project, the thing is that I made a database into MySQL Workbench with id primary key, auto increment , then some fields like username, password, firstname, lastname, and so on.
The goal is to make a login page and register page, for some reason if I push data with MySQL Workbench into the database it will let me retrieve it with my login form and my select statment, but for some reason I'm doing the same thing with register but in this case with the query INSERT.
So, after research, I did preparestatment and changed the executeQuery to executeUpdate and everything, but my log says a nullPointerException somewhere, I know it may be a simple and silly error that I'm not seeing, but I'm new at this. This is what U have made so far to insert data into my database:
public static UserBean registarUsuario(UserBean bean){
//preparing some objects for connection
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Error al cargar el driver");
System.out.println(ex.getMessage());
}
String firstname = bean.getFirstName();
String lastname = bean.getLastName();
String username = bean.getUsername();
String password = bean.getPassword();
boolean admin = bean.isAdmin();
int tipo = bean.getType();
String insertQuery =
"insert into idusuario (firstname,lastname,username,password,admin,tipo) values ('"+firstname+"','"+lastname+"','"+username+"','"+password+"','"+admin+"','"+tipo+"')";
System.out.println("Firstname is " + firstname);
System.out.println("Surname is " + lastname);
System.out.println("Query: "+insertQuery);
try
{
//connect to DB
currentCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
rs = stmt.executeQuery(insertQuery);
...
My output:
Info: Query: insert into idusuario
(firstname,lastname,username,password,admin,tipo) values
('jhon','marston','jmar','123','true','0') Info: Error :
java.lang.NullPointerException
The thing is that Netbeans doesn't even tell me where the NPE is happening so I'm kind of confused, I don't know if the query is wrong or if something else is, because as I can see in my output, the query seems ok.
I leave you here my database structure
You are assigining the stmt as null and never initializing it.
Statement stmt = null;
ResultSet rs = null;
Then you are trying to use it:
rs = stmt.executeQuery(insertQuery);
You will need to do something like this before you use it:
PreparedStatement stmt=currentCon.prepareStatement(yourQuery);
So, after research, i did preparestatment and changed the executeQuery
to executeUpdate and everything, but my log says a
nullPointerException somewhere, i know it may be a simple and silly
error that im not seeing, but understand that im new at this. this is
what i have made so far to insert data into my database
When we use insert,update or delete we need to use executeUpdate.
When we use select we need to use executeQuery.
In your example you are doing executeQuery for an insert. This is wrong. You need to use this:
rs = stmt.executeUpdate(insertQuery);
You're getting a NPE because you are trying to retrieve the results where there are none.
Here is a nice thing to do to help you reduce boilerplate code... (so you don't have to keep repeating yourself with db initialization values)
Create a class for your database connection:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/usuarios";
conn = DriverManager.getConnection(url,"root","admin");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Now you can use this in all your other classes like this:
public static UserBean registarUsuario(UserBean bean){
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("insert into idusuario (firstname,lastname,username,password,admin,tipo) values (?,?,?,?,?,?);");
pst.setString(1, bean.getFirstName());
pst.setString(2, bean.getLastName());
pst.setString(3, bean.getUserName());
pst.setString(4, bean.getPassword());
pst.setBoolean(5, bean.isAdmin());
pst.setInt(6, bean.getType());
pst.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
}
}
My insert into is giving me issues.
Im pretty sure the Jtextfield is the problem.
If anyone can give me a nudge in the right direction I would greatly appreciate it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#//localhost:1521/xe";
Connection conn = DriverManager.getConnection(url, "system", "oracle");
conn.setAutoCommit(false);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
Statement stm = conn.createStatement();
stm.execute(query1);
JOptionPane.showMessageDialog(null, "Record Added Succesfully.", "Record Added",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
nameTextField.getSelectedText()
I'm guessing that should be
nameTextField.getText()
Also, use a PreparedStatement for the SQL. You will less likely to make SQL syntax errors. Check out: geting data from multiple table when selecting a row then clicking a button for a basic example.
Im pretty sure the Jtextfield is the problem.
Well, learn how to do some basic debugging instead of guessing.
String query1 = "INSERT INTO WIN(NAME) VALUES('"+nameTextField.getSelectedText()+"')";
The above code can be written like:
String name = textField.getSelectedText();
// now you can verify the value of the name
System.out.println(name);
String query1 = "INSERT INTO WIN(NAME) VALUES('"+ name +"')";
// verify SQL syntax
System.out.println( query1);
Of course my first suggestion to use the PreparedStatement is easier, but learn how to display the value of variables when you do debugging.
good day, i have a problem with this method, for some reason it gives me an error. "Java.sql.SqlException: statement is not executing". But it checks if the value is duplicate and prompts the error as the method below show. This has stopped my registration from completing. thanks for your help
public static void UserExists(String y){
try{
query = " select * from MailRegister where Username=?";
pst = connect.prepareStatement(query); //passes my query to java predefined prepared statement
pst.setString(1, Username.getText()); //passes the value of the username to the prepared statement
rs = pst.executeQuery(); //this would execute the query passed in the prepared statement
if(rs.next()){
JOptionPane.showMessageDialog(null, " Sorry This Username is Taken");
}
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);//shows error dialog
}
}
You probably get this error because your objects are not closed properly all the time. Your connect is breaking. A good practice is to open and close the connection when required to prevent leaks.
In the code above, pst.close(); and rs.close(); should be in a finally.
Or even cleaner, the prepared statement should go inside a :
try (pst = connect.prepareStatement(query)) {...}
That way you don't have to close it yourself, the JVM will handle it for you.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/pizzabaseaccount", "root", "");
Statement st = con.createStatement();
String sql ="insert into pizzaorder (PizzaType,PizzaChosen,ToppingsDetails,CrustType,PizzaSize,PizzaQuantities,PizzaTotalPrice)"
+"values ('"+pizzatype+"','"+pizzachosen+"','"+toppingsdetails+"','"+crusttype+"','"+pizzasize+"','"+pizzaquantities+"','"+totalprice+"')";
st.executeQuery(sql);
JOptionPane.showMessageDialog(null, "Order Complete");
}catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error");
}
I get "Error". It wont insert the data on the pizzabaseaccount database. pizzaorder is the table name btw. I don't know whats wrong with the code. Im a beginner on Java. Btw, the pizzatype , pizzachosen, toppingdetails, crusttype, pizzasize, pizzaquantities, and totalprice are String variables.
Check that pizzatype pizzachosen and all the others do not contains the "'" carachter; if so, you should escape it.
Anyway, this is not a good way to create an SQL query.
Use bind parameters --> read the API reference