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.
Related
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);
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();
}
}
I've encountered an error and I'm not able to figure out my mistake. I've done my research and haven't found an appropriate answer for my question.
This is my code:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String CN, CNo, MN, NT, SNo, VIP, T, D;
CN = TF1.getText();
CNo = TF2.getText();
MN = TF3.getText();
NT = TF4.getText();
SNo = TF5.getText();
VIP = TF6.getText();
T = TF7.getText();
D = TF8.getText();
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/devika", "root", "rockgirl12");
Statement stmt = (Statement) con.createStatement();
String query = "INSERT INTO Maintenance VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record added succesfully!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
What I'm trying to do here is I'm adding data to my SQL database through a form I designed in Java Netbeans. I've attached the form I've created here.
My Form
Help would be greatly appreciated :)
Exactly what the error says. The number of columns and the fields in valules do not match. This sort of insert without specifing the column names isn't the best practice by any stretch. You should do
String query = "INSERT INTO Maintenance(col1, col2, col3, col4,..) VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
In fact, you shouldn't be doing this sort of string concatenation either. It's far better to use prepared statements. The current approach does not ensure that the data is properly escaped before being saved.
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
i have the following jframe :
and i wanna make the buttons work im still new to programming can someone help me please? i want the add row btn to add a new row to database, the update btn let me save changes and delete delete the selected row, also the jTextBoxes are connected to the database
i tried doing this to update :
Connection conn=null;
PreparedStatement pst = null;
try{
String value1=txt_cid.getText();
String value2=txt_carid.getText();
String value3=txt_aid.getText();
String value4=txt_rd.getText();
String value5=txt_bd.getText();
String value6=txt_bn.getText();
String sql="update booking set customer_id'"+value1+"',car_id'"+value2+"',agency_id'"+value3+"',return_date'"+value4+"',booking_date'"+value5+"',booking_number'"+value6+"',";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "table updated");
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
but it didnt work out for me i get exception error
You haven't stated what the error is but UPDATE takes an equals operator for every parameter. Also use PreparedStatement placeholders to avoid SQL Injection attacks:
String sql = "update booking set customer_id=?, car_id=?,agency_id=?,return_date=?,booking_date=?,booking_number=?";
pst = conn.prepareStatement(sql);
pst.setInt(1, value1);
pst.setInt(2, value2);
... // set the other parameters
Read: UPDATE Syntax