i want to insert a row of data into my USERS table...
this is my code
#FXML
private void handleRegisterButtonAction() throws SQLException{
String userName="'"+txt_username.getText()+"'";
String password="'"+txt_password.getText()+"'";
String mail="'"+txt_userMail.getText()+"'";
//for example user id is 22
int userId=22;
String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
+ " VALUES("+userId+","+userName+","+password+","+mail+");";
stmt.execute(insertUser);
}
the code runs but table in the database doesn't change
this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this
Write query like this :
INSERT INTO **Database_Name**.dbo.USERS(userId,userName,userPassword,userEmail)"
+ " VALUES("+userId+","+userName+","+password+","+mail+");";
Change Database_Name to your database name, then run your code.
First of all use PreparedStatements because if the userName or password have illegal characters you will have problems with your database .
Example character ' and boom the insert will not work.
PreparedStatement statement = dataBaseConnection.prepareStatement( INSERT INTO '"+tableName+"' (userId,userName,userPassword,userEmail) VALUES(?,?,?,?)");
//Add the data to the table
statement.setInt(1,userId); //better to user autoincrement
statement.setString(2, userName);
statement.setString(3, password);
statement.setString(4,userEmail);
//Execute the update
statement.executeUpdate();
//commit in case you have turned autocommit to false
databaseConnection.commit();
Observe carefully the statement cause you can see on the table name i have ' and ' single column before and after the name of the table.
Related
I have a SQLite database with a list of all airports in the world with their respective data (code, country, name, etc). I'm trying to create a method where an ATC will login with their airport's code. The program will then check if the airport code exists, and return true so the ATC can login and will be able to see all the information of their airport. If it doesn't exist, it returns false and doesn't let the ATC login.
I'm trying to see if a specific "item" exists in the database, not a row or column.
By looking online this is the "closest" I've gotten, but I'm getting an error and can't figure out how else to do it right now.
String selectSQL = "IF EXISTS(SELECT 1 FROM airports WHERE code = " + ATCLogin + ")";
The error I'm getting now is
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "'MAD'": syntax error)
"MAD" is the airport code I'm testing right now.
First, the raw SQL query you want would look something like this:
SELECT EXISTS (SELECT 1 FROM airports WHERE code = ?)
Note that the above query should return a single boolean true/false value. The ? is a placeholder, to which you should bind a Java string value. Here is how you can do that with a Java prepared statement.
String sql = "SELECT EXISTS (SELECT 1 FROM airports WHERE code = ?)";
String code = "LAX";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, code);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
boolean result = rs.getBoolean(1);
String output = "Airport code " + code + " exists in database? " + result;
System.out.println(output);
}
I am trying to connect my java project with database in netbeans. I have a table named task_table and i'm trying to add some values on that table.
Here is my code
Connection con1;
PreparedStatement insert;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String name1= addtaskname.getText();
String name2= addtaskdate.getText();
String name3= addtasktime.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/jesin_virtual","root","");
insert = con1.prepareStatement("insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)");
insert.setString(1, name1);
insert.setString(2,name2 );
insert.setString(3,name3);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Task Added sucessfully");
and i got this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax
The problem is here:
insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)
^ ^ ^
If the column names really contain blanks, then you need backticks around the names (`Task Name`), else change the names to what they really are (Task_Name maybe?).
Please correct SQL query inside as below...
if in your database column names contains space so please use below query
"insert into task_table("Task Name","Task Date","Task Time") values (?,?,?)"
if in your database column names contains _ so please use below query
"insert into task_table(Task_Name,Task_Date,Task_Time) values (?,?,?)"
what is the best way to check if the user is exist
i have wrote this code
try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();
}
my friends told me that this is stupid query
and i should do like this
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");
Your friend is right. You can check if row exists by query:
SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)
As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine.
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore.
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are.
When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection.
But
Inserting a new user to the database is not the right way to do user validation.
You can do something like this example:
String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setString(2, "1234");
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
//You will need user information to render dashborad of your web application
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}
Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?
Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!
In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().
Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code
My source code has the following structure:
SourceFolder
AddProduct.jsp
Source Packages
-Controller(Servlets)
SaveProduct.java
-Model(Db Operations)
ProductDbOperations.java
I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id).
To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.
Also, I am not using any Framework and am using Netbeans 7.3.
Problem:
A new entry is inserted into the product table with this piece of code
IN: ProductDbOperations.java
try
{
this.initConnection(); // Db connection
pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
rs = pst.executeUpdate();
}
catch(SQLException ex)
{
}
I Also used the solution at following link which doesn't works for me.
I didn't got any SQL exception
How to get the insert ID in JDBC?
so help me find out why this code not working for me .
Thanks a million.
Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience)
Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.
// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();
// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
long productId = rs.getLong(1);
}
Note that the column name passed to the call is case-sensitive. For Oracle the column names are usually uppercase. If you are using e.g. Postgres you would most probably need to pass new String[] {"product_id"}
The way you are using is not the proper way of using preparedstatement
use the following way
pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();
Yes there is a way to retrieve the key inserted by SQL. You can do it by:
Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert
e.g:
String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);