Insert into database - java

I have a problem, I have a system to add users, I have to make check if this user exist before so that i will not add him again, I retrieved all the name from database into an arraylist.I check first if the array list is empty so that I can add the user else he will check if he exists or not
here is the code
if(names.size() == 0){
dbstatement.executeUpdate("
insert into users (user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
JOptionPane.showMessageDialog(rootPane, "user added successfully");
}
else{
for (int i = 0; i < names.size(); i++) {
if (username.equals(names.get(i))) {
JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist");
break;
}
}
dbstatement.executeUpdate
("insert into users(user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
}
the problem is when the program found a name exist before he told me and add him, i know the cause of this problem all i want to know where to but else of the if inside for loop, I want him to tell me the user exist onlyy not to add it again

Just use the SQL WHERE clause to see if the username exist. There's absolutely no need to copy the entire DB table into Java's memory.
preparedStatement = connection.prepareStatement("SELECT id FROM users WHERE user_name = ?");
preparedStatement.setString(1, username);
resultSet = preparedStatement.executeQuery();
boolean exist = resultSet.next();
Wrap this in a method like boolean exist(String username) and rearrange your code flow as follows:
if (exist(username)) {
// Show warning message.
} else {
// Insert into DB.
}
Note that PreparedStatement is been used instead of Statement. This prevents your code from SQL injection attacks.

Just call the database with each name to add.
Let the sql try to insert the name. It will either insert or throw a key violation (assuming you have a unique constraint on the name).
If it throws a key violation you know the name is already in the database.
If it does not throw an error then the name was inserted.
Read/decide/write style processing is not the way to make this work. It can still have issues when another process inserts a new name in the time between the read and the write. This means that you still have to check for key violations anyway. If you have to check for key violations anyway you might as well do it right the first time and just try inserting all the names.

if(names.size() == 0){
dbstatement.executeUpdate("
insert into users (user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
JOptionPane.showMessageDialog(rootPane, "user added successfully");
}
else{
if ( names.contains(username) ) {
JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist");
}
else {
dbstatement.executeUpdate
("insert into users(user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
}
}

Related

How to update a row of entries in a database (JavaDatabase) that is connected to my JTable?

I am making a program without knowing much about programming... I used some youtube videos to help me.
My program is made for a chef that can edit users & food and gather ratings and suggestions from the inspector. The chef's section of editing users' details works.
However, the inspector's rating does not as it throws an error: SQLSyntaxException: Encountered "Vegetarian" at line 1, column 65. I believe it is because of getting the rating value (which is int) in a wrong way...
'
public void getConnection(){
try{
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1327/MyApp", "Me", "Me");
mystatObj=myconObj.createStatement();
myresObj=mystatObj.executeQuery("Select * from Me.Food");
tableRateFood.setModel(DbUtils.resultSetToTableModel(myresObj));
}
catch (SQLException e){
e.printStackTrace();
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "update Me.Food set Name = '" + nameText.getText()
+ "',Type = '" + typeText.getText()
+ "', Rating = '" + ratingText.getText()
+ ", 'Vegetarian = '" + vegetarianText.getText()
+ "', ShownOnMenu = '" + showText.getText()
+ "' where Id = " + idText.getText();
//tried the following... did not work either
/*+ " Rating = " + Integer.parseInt(ratingText.getText()));*/
Statement update= myconObj.createStatement();
update.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Updated successfully!");
}
catch(SQLException E){
E.printStackTrace();
}
getConnection();
}
Your forgot a quote in ", 'Vegetarian = '"
Talking about building query strings, you should avoid +-ing values and rely on prepared statements with sql parameters instead. Allows the database to cache the query and avoids sql injection attacks. And spares you formatting headache, think about date values.

How to Delete rows in table using Variable in SQL

How should I delete a row using a java variable in SQL table?
I am trying to delete a record from table member (with two columns, name and year) using what the user has input (variable newName and newYear). I want to find the row that has the same record as what the user has input (name = newName && year=newYear) and delete it. However, this code doesn't change anything on the table (no row is deleted although what I have input is correct). What's wrong with my code?
String newName = memName.getText();
int newYear = parseInt(memYear.getText());
are the variables used in the code below.
try {
s = c.createStatement();
t = "DELETE FROM member " +
"WHERE (name='" + newName + "'&& year='" + newYear + "')";
s.executeUpdate(t);
s.close();
c.commit();
c.close();
} catch (SQLException ex) {
Logger.getLogger(AddMember.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(null, "Saved.");
memName.setText(null);
memYear.setText(null);
I want the row with the info the user input to be deleted from the table, but it didn't make any changes to my table.
the problem you have is that in SQL you cannot use && instead use AND as shown in the following code:
t = "DELETE FROM member " +
"WHERE (name='" + newName + "' AND year='" + newYear + "')";

SQL database update statement not working

ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;

Trying to find if an item exists in database table, if it doesn' t exist. add it

I am trying to develop a program where you want to add a new book ( title, author, date,...)
but i do not want to add the author multiple times..
i want the program to check if the author already exists in the table, if not it will add him... here is my code :
public void insert_bk(String m, String a, String b, String c, String d, String e) {
String sql="Select * from author where Full_Name='"+b+"'";
System.out.println(sql);
try {
opencn();
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while (rs.next()) {
String id=rs.getString("Author_ID");
System.out.println(id);
st.executeUpdate("INSERT into book (`Book_ID`,`Title`,`Author_ID`,`Date_of_release`,`Theme`,`Edition`)"+ "VALUES ('" + m+ "','" + a+ "','" + id+ "', '" + d+ "', '" + e+ "', '" + c+ "')");
}
}
catch(SQLException exp) {
System.out.println(exp.getMessage());
}
}
In this code it just checks if the Author exists and adds the book... how can i make the condition that if the author does not exist it will add him along with the book?
Any ideas?
Thank you in advance :)
Instead of using a while-loop you should put rs.next() into an if-statement. If the call returns false no author is present and it has to be inserted.
you can do this stored procedure
declare #i int
Select #i=count(*) from author where Full_Name=#FullName
IF(#i < 1)
BEGIN
// INSERT
END
This might help
String query = "Select * from author where Full_Name='"+b+"'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr;
con.Open();
cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
if (rdr.Read()) { // if you have an author
//do your updation code here
}
else {
//if rdr.Read() gives 0 which will be the case when our
//author wont exist past the code for adding an author here
}
You can make a conditional insert by adding the keyword IGNORE into the statement. Depending on which SQL database you are using the answer is slightly different. I'll demonstrate here the two ways for MySQL and sqlite, but of course there are more.
For MySQL
INSERT IGNORE INTO authors VALUES(?,?...,?)
For SQLite
INSERT OR IGNORE INTO authors VALUES(?,?,...,?);

Add backslash to Varchar in MySQL

I've created this little quiz for a school project using Java and MySQL. Now My project runs fine but as an experiment i tried to add images in my question. The Question jFrame takes the question and all options directly from a database called ques having 8 columns last of which is "path" which is a varchar(500). Here is my Java code to add questions :-
try {
Class.forName("java.sql.Driver");
Connection con = (Connection) DriverManager.getConnection(jdbcurl, user, pass);
Statement st = con.createStatement();
ResultSet rt = st.executeQuery("SELECT qno from ques order by qno desc limit 1");
// get last qno primary key
for (; rt.next(); ) {
qno = (Integer) rt.getObject(1); // save qno as int
}
nqno = qno + 1; // create new qno
if (path == null){
String query1 = "insert into ques values (" + nqno + ",'" + question + "','" + ans1 + "','" + ans2 + "','"
+ ans3 + "','" + ans4 + "','" + ca + "',null);"; // ca is correct answer and null is path
Statement st1 = con.createStatement();
st1.executeUpdate(query1);
System.out.println("query : "+query1);
JOptionPane.showMessageDialog(this, "Question added successfully! Without Image");}
else {
String query1 = "insert into ques values (" + nqno + ",'" + question + "','" + ans1 + "','" + ans2 + "','"
+ ans3 + "','" + ans4 + "','" + ca + "','"+path+"');";
System.out.println("query :" +query1);
Statement st1 = con.createStatement();
st1.executeUpdate(query1);
JOptionPane.showMessageDialog(this, "Question added successfully! with image");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error in code");
The query sent was
query :insert into ques values (12,'123','123','123','123','123','123','F:\JavaQuiz\src\javaquiz\About.png');
All okay, no exception handled.
But in the SQL the path is saved so :- F:JavaQuizsrcjavaquizAbout.png
The database omits the backslashes. I want it not to do so. So that later I can call this link in my Question.java
Please.. Any suggestion?
(I'm sorry I'm new to programming so sorry if this is a dumb question)
User PreparedStatement instead of Statement and set the parameters. This will set the correct String with required escape characters.
String query1 = "insert into ques values (?,?,?,?,?,?,?,?)";
PreparedStatement ps=connection.prepareStatement(query1);
ps.setInt(1,nqno);
ps.setString(2,question);
ps.setString(3,ans1);
ps.setString(4,ans2);
ps.setString(5,ans3);
ps.setString(6,ans4);
ps.setString(7,ca);
ps.setString(8,path);
ps.executeUpdate();
and do the try..catch for exceptions.
In java (and C,C++,C#) string the backslash character is a special "escape" character. You need to use \\ to represent a backslash, or change your insert to use parameters using prepared statements rather then be a string.
See Java Character Escape Code Reference
(Or just change your path to use / slashes).

Categories

Resources