Very Strange error when trying to INSERT into a database with more than 1 entry - mysql

HOPEFULLY.....the title makes sense. But basically this is what is going on. I'm creating a form where a user will be able to View, Update, Insert and Delete records from tables within a database.
I'm using a combo box to display the table data:
Now If I try to Insert a new record, it works fine, until I try and more than one.
This is me placing just the personID record in. and it works fine:
But if i try and add a personID AND a firstName this happens:
as you can see, it ignores the personID entry, and just goes for the firstName.
I cant go further in my code without figuring out what is causing me to not be able to put in 2 things at once.
Here is my INSERT code:
string myInsertSQL;
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "personID)";
myInsertSQL += " VALUES ('";
myInsertSQL += personID.Text + "')";
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "firstName)";
myInsertSQL += " VALUES ('";
myInsertSQL += firstName.Text + "')";
MySqlConnection conn = new MySqlConnection(connstring);
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
With the above, it will only insert the firstName.
I have no idea why this would happen, and I would love some input. Thanks!

By doing this, the DB would insert the ID and the firstname on 2 distinct rows, if you didn't overwrite the first string (myInsertSQL = "INSERT INTO person(";). Here, it only performs the second query (i.e. inserting first name).
Try:
myInsertSQL = "INSERT INTO person(";
myInsertSQL += "personID, FirstName)";
myInsertSQL += " VALUES ('";
myInsertSQL += personID.Text + "', '"+ firstName.Text +"')";
Please note that this is wide open to SQL injections. Try to use prepared statements instead of directly injecting plain text into queries:
string myInsertSQL = "INSERT INTO person(personID, firstName) VALUES (#personID, #firstName)";
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
cmd.Parameters.AddWithValue("#personID", personID.Text);
cmd.Parameters.AddWithValue("#firstName", firstName.Text);
EDIT :
According to your comment, you try to insert more than those 2 values. This work the same.
The error says that you did specify a different number of values and fields. You speak of 6 values, but only list 5 (personID, firstName, address, phoneNumber, postCode). I suspect you forgot the lastName:
string myInsertSQL = "INSERT INTO person(personID, lastName, firstName, address, phoneNumber, postCode) ";
myInsertSQL += "VALUES (#personID, #lastName, #firstName, #address, #phoneNumber, #postCode)";
MySqlCommand cmd = new MySqlCommand(myInsertSQL, conn);
cmd.Parameters.AddWithValue("#personID", personID.Text);
cmd.Parameters.AddWithValue("#lastName", lastName.Text);
cmd.Parameters.AddWithValue("#firstName", firstName.Text);
cmd.Parameters.AddWithValue("#address", address.Text);
cmd.Parameters.AddWithValue("#phoneNumber", phoneNumber.Text);
cmd.Parameters.AddWithValue("#postCode", postCode.Text);
// and so on...

myInsertSQL = "INSERT INTO person(";
here you completely overwrite the myInsertSQL String, so whatever you put in there before is gone before you even send it to the database.

You are overwriting variable value
myInsertSQL += personID.Text + "')";
myInsertSQL = "INSERT INTO person(";

Related

JDBC insert data into MySql table from txt file

I want to read data from txt file and insert them into a mysql database but i get error int the sql syntax.Μy sql code is given below:
`Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
java.sql.Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
stmt = (Statement) conn.createStatement();
String sql = "INSERT INTO `data_db` (location , instrument,date_time,data)"+
" VALUES ('" + location + "','" + instrument + "',''" + date_time + "','" + blob + "')";
stmt.executeUpdate(sql);
`
What is the problem?
location, instrument, date_time and blob are strings...
The table has an id column that is auto-incremented...
Could you share the error message of the sql code?
AFAIK, it may be a redundant single quote between your instrument and date_time variables.

SQL INSERT with parameter as query

How can I insert parameter with value from database.
I have some field and I should insert value from this database + 1 (with plus one)
For example
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_nr, #game_player_id, #game_nrontable, #game_role_id)"
'Example
myCommand.Parameters.Add("#game_nr", SqlDbType.Int).Value = **"(SELECT MAX(GAME_NR) FROM GAMES)" + 1**
You don't. You make GAME_NR and auto-incremented primary key:
create table games (
game_nr int auto_increment primary key,
. . .
);
Then you do the insert as:
INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID)
VALUES (#game_player_id, #game_nrontable, #game_role_id);
Let the database do the work.
You don't need the parameter, you can try following code.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_NR, GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES ((SELECT MAX(GAME_NR) + 1 FROM GAMES), #game_player_id, #game_nrontable, #game_role_id)"
But it looks like a primary key of the table. If Game_Nr is pr, You should use auto-inc. identity, then you don't need this param.
It will be.
myCommand.CommandText =
"INSERT INTO GAMES (GAME_PLAYER_ID, GAME_NRONTABLE, GAME_ROLE_ID) " &
" VALUES (#game_player_id, #game_nrontable, #game_role_id)"

Combining 2 insert into in one command

I couldn't figure this out:
I want to add a row in a table-a and 3 columns of this row will come from table-b and other 2 columns will come from e.g textboxes...
This code didn't work...
SqlCommand cmd35 = new SqlCommand("INSERT INTO BTmr (Barcode,[Machine Name],[Machine ID]) SELECT Barcode,[Machine Name],[Machine ID] FROM BkmP WHERE barcode like '" + c13 + "%' UNION INSERT INTO BTmr([Repair Cost],[Repair Date],Barcode)values (#cst,#rprd)", connection);
cmd35.Parameters.AddWithValue("#cst", textBox10.Text);
cmd35.Parameters.AddWithValue("#rprd", dateTimePicker1.Text);
Just put the parameters as static values in the select statement.
SqlCommand cmd35 = new SqlCommand("INSERT INTO BTmr (Barcode,[Machine Name],
[Machine ID],[Repair Cost],[Repair Date]) SELECT Barcode,[Machine Name],
[Machine ID],#cst AS [Repair Cost],#rprd AS [Repair Date] FROM BkmP WHERE
barcode like '" + c13 + "%', connection);
cmd35.Parameters.AddWithValue("#cst", textBox10.Text);
cmd35.Parameters.AddWithValue("#rprd", dateTimePicker1.Text);
While your're at it, parameterize that where clause: https://stackoverflow.com/a/251380/123422

insert statement difficulty

this is where I am getting my info from, and when I choose the address it fills in all the info
but the problem starts when I try to add a renter to the renter table after I have deleted a renter. this table no longer shows columns with all addressIDs so I am trying to insert the AddressID as well from the property table.I hope this makes sense
I cant insert pictures yet, but here is what it looks like when i chose a property, rentals
if ( ( evt.getStateChange() == java.awt.event.ItemEvent.SELECTED ) &&
( PropertyComboBox.getSelectedIndex() != 0 ) )
{
Address = ( String ) PropertyComboBox.getSelectedItem();
try {
myResultSet = myStatement.executeQuery(
"SELECT Property.Address,Property.AddressID,Property.RentAmt, Renter.RenterID, Renter.AddressID, Renter.FirstName, Renter.LastName, Renter.CellPhone, Renter.DepositPaid,Renter.DepositAmtPaid " +
"FROM Property, Renter " +
"WHERE Property.Address = '" + Address + "'" + "AND Renter.AddressID = Property.AddressID" );
if (myResultSet.next())
{
renterID = (myResultSet.getString("Renter.RenterID"));
addressID = (myResultSet.getString("Property.AddressID"));
txtRentAmt.setText(myResultSet.getString("Property.RentAmt"));
txtShowAddressID.setText(myResultSet.getString("Property.AddressID"));
txtShowRenterID.setText(myResultSet.getString("Renter.RenterID"));
txtFirstName.setText(myResultSet.getString("Renter.FirstName"));
txtLastName.setText(myResultSet.getString("Renter.LastName"));
txtCellPhone.setText(myResultSet.getString("Renter.CellPhone"));
txtDepositPaid.setText(myResultSet.getString("Renter.DepositPaid"));
txtDepositAmtPaid.setText(myResultSet.getString("Renter.DepositAmtPaid"));
if(myResultSet.getString("Renter.DepositPaid") == ("Y"))
{
txtDepositPaid.setText("Y");
}
else
{
txtDepositPaid.setText("N");
}
}
}
can someone help me with this ? I am trying to insert a new renter
from a netbeans jform into my database. The AddressID
(PK,auto-increment ) from the property table should automatically
insert into the renter table AddressID (FK, auto-increment(so I
thought)
It will insert if I use this statement but then the addressID shows as
NULL, not the AddressID from the property table, which I need. Ive
been working on this since Saturday. UGH Please help! very simple, yet
I cannot figure it out
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid)"
+ " VALUES (" + addressID + ",'"
+ addFirstName + "','"
+ addLastName + "','"
+ addCellPhone + "','"
+ addDepositPaid + "',"
+ addDepositAmtPaid + ")" + " WHERE Property.AddressID = " + addressID ;
INSERT plus WHERE? i guess you need UPDATE, not INSERT http://dev.mysql.com/doc/refman/5.0/en/update.html
EDIT: it's not clear, you are mixing in insert in one table with a where in another table?, just do "INSERT ... (fields) VALUES (values)" without WHERE and specify all addressID on fields.
You need to specify AddressID in the field list.
...INTO Renter (AddressID, FirstName...
Assuming that you specify all columns in the table, you can omit the field list.
You may also be more comfortable with the INSERT ... SET syntax.

Insert with Hibernate native query does not work for java.util.Date

I am using Hibernate JPA and Spring with a Mysql database and I want to insert using a SQL statement like this:
Date saveDate = new Date();
java.sql.Timestamp timeStampDate = new Timestamp(saveDate.getTime());
Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
+ true +", " + timeStampDate + ", " + description + ", " + title + ", "
+ needsLevelId + ", " + patientId + ", " + userId + " )");
persistableQuery.executeUpdate();
But after running it I get the following error:
WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: -11, SQLState: 37000
ERROR: org.hibernate.util.JDBCExceptionReporter - Unexpected token: 15 in statement
[INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE,
NEEDS_LEVEL_ID, PATIENT_ID, USER_ID)
VALUES (true, 2011-03-01 15?, any description, , 193, 1, 3 )]
Could someone help me on this please?
PS. I am aware of using hibernate in non-native way, but I need to use native way. I am also of insert ...from... , but I don't think it will help.
Finally I think the problem is mainly with the date. How do you guys pass on MySQL a datetime type using Java?
Update:
The following works fine, I guess it is a java date to mysql datetime conversion problem.
("INSERT INTO TASK_ASSESSMENT "
+ "(ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, "
+ "NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) "
+ "VALUES (true, 1999-12-22, '" + description + "', '"
+ title + "', " + needsLevelId+", " + patientId
+ ", " + userId + ")");
Could anyone please help me on how to convert java.util.Date to MySQL datetime?
Don't use concatenation to insert data into queries, use parameters instead. It solves problem with wrong representation of values, as well as many other problems:
entityManager.createNativeQuery(
"INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (?, ?, ?, ?, ?, ?, ?)")
.setParameter(1, true)
.setParameter(2, saveDate, TemporalType.TIMESTAMP) // Since you want it to be a TIMESTAMP
.setParameter(3, description)
.setParameter(4, title)
.setParameter(5, needsLevelId)
.setParameter(6, patientId)
.setParameter(7, userId)
.executeUpdate();
Looks like a few issues. Some of your fields should have quotes around them. Also, possibly you need to format the timestamp in a different way, not sure how mysql expects it?
Query persistableQuery = entityManager.createNativeQuery(
"INSERT INTO TASK_ASSESSMENT
(ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, "
+ "TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES ("
+ true +", "
+ "'" + timeStampDate + "'"
+ ", "
+ "'" + description + "'"
+ ", "
+ "'" + title + "'"
+ ", "
+ "'" + needsLevelId + "')");
As far as formatting the date, I suspect you will need to look at the SimpleDateFormat class, which will let you get the date into whatever format mysql expects. See http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
You can send parameter in method save, or what you use and use named SQL queries Query persistableQuery = entityManager.createNativeQuery("INSERT INTO TASK_ASSESSMENT (ACTIVE_FLAG, ASSESSMENT_DATE, DESCRIPTION, TITLE, NEEDS_LEVEL_ID, PATIENT_ID, USER_ID) VALUES (":active_flag",":timeStampDate", ":description", ":title", ":needsLevelId", ":patientId", ":userId" )").setParameter("active_flag", your_object.getactive_flag).setParametr and etc
persistableQuery.executeUpdate();
but somewhere create object with all this fields.
In hibernate 5.3 and above positional parameters are deprecated so we need to use keys for parameter. Hql does not support insert with parameter. We need to follow below approch
import org.hibernate.query.Query;
public void insertData() {
String sql = "insert into employee(id,name,age,salary) values(:0,:1,:2,:3)";
List<Object> paramList = new ArrayList<Object>();
paramList.add(1); // id
paramList.add("sumit"); // name
paramList.add("23"); // age
paramList.add(10000); // salary
Session session = null;
try {
session = getSessionfactory().openSession();
Query query= session.createNativeQuery(sql);
for(int i=0;i<paramList.size();i++) {
query.setParameter(""+i,paramList.get(i)); // remember to add "" before i , we need to maintain key value pair in setParameter()
}
query.executeUpdate();
}
catch(Exception e) {
System.out.println(e);
}
}