Here's the syntax:
string insert_query = "insert into book_borrow (BookID, MemberID, Date_Borrow, Date_Return) values ('" + BookID + "', '" + MemberID + "', curdate(), dateadd(month,1, getdate()))";
const char* q = insert_query.c_str();
qstate = mysql_query(conn, q);
I have error to query execution Problem! 1305
I want to automatically add return date after current date but I can't get it.
For MySQL, it will be DATE_ADD() not dateadd(), document can be found here.
Also do not trust user input like BookID and MemberID to prevent SQL injection. Try using prepared statements.
Try the below SQL
string insert_query = "insert into book_borrow (BookID, MemberID, Date_Borrow, Date_Return)
values ('" + BookID + "', '" + MemberID + "', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 MONTH))";
Related
I am currently working with a database which the dates are stored as strings in the (DD/MM/YYYY) format.
I am currently attempting to find a range of dates i.e. (15/07/2017 - 26/07/2017) which will then populate a weekly list.
The issue I am having it because these values are stored as strings within SQL I am unable to select a range unless I specify the values.
I am wondering are there any SQL Wizards out there who can help me.
Thanks,
Joe
you can use between and str_to_date eg:
select *
from my_table
where str_to_date(my__date_column, '%d/%m/%Y')
between str_to_date('15/07/2017', '%d/%m/%Y')
and str_to_date('26/07/2017', '%d/%m/%Y')
Hello Everyone I amended my answer as the previous one was incorrect and unhelpful to other users. In short I had to change the Dates to be stored as Dates correctly within SQL. In short there was no short cut unfortunately.
This is a the SQL Query which i used (No SQL Injection Protected), I hope this is helpful
"SELECT * FROM placement WHERE ('" + StartDate.ToString("yyyy-MM-dd") + "'
between StartDate and EndDate OR '" + EndDate.ToString("yyyy-MM-dd") + "'
between StartDate and EndDate or StartDate = '" + StartDate.ToString("yyyy-
MM-dd") + "' or EndDate = '" + StartDate.ToString("yyyy-MM-dd") + "' or
StartDate = '" + EndDate.ToString("yyyy-MM-dd") + "' or EndDate = '" +
EndDate.ToString("yyyy-MM-dd") + "') AND YearGroup = '" +
User.IntakeYear.ToString() + "' AND Cohort = '" + User.Cohort.ToString() +
"';";
Thanks For Your Feedback.
I am using VB.net to access a MySQL database and insert data into this table.
I am getting this data from an opera database, the query I am using is:
Dim queryInsert As String = "INSERT INTO customer_company(customer_id, name, street, zip,
city,country,comments) values(" + c.sn_account.Trim + ", " + name + ", " + road + ", "
+ postcode + ", " + city + ", " + country + ", " + name + ")"
I am then getting an error when it comes to the record:
B010, Charles Birt & Co, Loch House, null, Tenby, Dyfed, Charles Birt & Co
I though that this may be the '&' in the data so I have tried replacing it with || chr(38) || and also escaping it using \& but these do not work. Also I tried setting the postcode to various things like 'N/A', ' ' and null because this particular record doesn't have a postcode but this still gives the error.
Don't know if its the data or the query, any suggestions would be great.
Please use parameters when executing SQL commands.
This avoids problems like you encounter in your question and also minimizes SQL injection attacks:
Dim queryInsert As String =
"INSERT INTO customer_company(customer_id, name, street, zip,city,country,comments) values (#customer_id, #name, #street, #zip, #city, #country, #comments)"
Dim cmd as new MySqlCommand(queryInsert, <YourConnection>)
cmd.Parameters.AddWithValue("#customer_id", c.sn_account.Trim)
cmd.Parameters.AddWithValue("#name", name)
cmd.Parameters.AddWithValue("#street", road)
cmd.Parameters.AddWithValue("#zip", postcode)
cmd.Parameters.AddWithValue("#city", city)
cmd.Parameters.AddWithValue("#country", country)
cmd.Parameters.AddWithValue("#comments", name)
cmd.ExecuteNonQuery();
Not too sure if this will fix your problem but, when adding/inserting a value with a String Data Type Column in SQL, you should have ' '.
in your example:
Dim queryInsert As String = "INSERT INTO customer_company(customer_id,
name, street, zip, city,country,comments)
values(" + c.sn_account.Trim + ", '" + name + "', '" + road + "', "
+ postcode + ", '" + city + "', '" + country + "', '" + name + "')"
i dont add ' ' in customer_id and postcode because i think that they are not string date type.
I have syntax error in this code
string JSS_connetionString011 = null;
OleDbConnection JSS_connection011;
OleDbDataAdapter JSS_oledbAdapter011 = new OleDbDataAdapter();
string JSS_sql011 = null;
JSS_connetionString011 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/je_salestoredb.mdb;Persist Security Info=True;Jet OLEDB:Database Password=JEPTUSJSSJes";
JSS_connection011 = new OleDbConnection(JSS_connetionString011);
JSS_sql011 = "update product set Siv_Sales_Invoice_NO = '" + textBox1.Text + "' , prod_Status = '" + JSS_product_Status + "' , prod_SALED_ftrCalc = '" + textBox10.Text + "' , piv_SALED_DATE = '" + dateTimePicker1.Text + "' , sivd_ID = '" + textBox3.Text + "' , prod_ROOM ='" + JSS_product_Warhousee + "' where( prod_COMPANY = '" + comboBox4.Text + "' and prod_MODEL = '" + comboBox5.Text + "' and prod_Status = '" + JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
JSS_connection011.Open();
JSS_oledbAdapter011.UpdateCommand = JSS_connection011.CreateCommand();
JSS_oledbAdapter011.UpdateCommand.CommandText = JSS_sql011;
JSS_oledbAdapter011.UpdateCommand.ExecuteNonQuery();
Syntax error (missing operator) in query expression '( prod_COMPANY = 'NSN' and prod_MODEL = '606' and prod_Status = 'true' ORDER BY prod_COMPANY LIMIT 1 )'.
There are many records with the same conditions of the query sentence, but each of them have different id.
Any Ideas?
Okay, a couple of things:
One, you can't use ORDER BY or LIMIT in an UPDATE statement in an Access database. The example you linked to is for MySQL, a different database.
Two: What Jon Skeet says is absolutely true: you need to use parameterized SQL rather than putting values directly in SQL.
Three: Given that ORDER BY and LIMIT are not valid in Access update statements, if you replace this bit of code:
+ JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
... with this:
+ JSS_Ready_For_Sale + "')";
... the syntax error, or at least that syntax error, may go away.
You might also want to be put a space between the WHERE and the (. I don't know that that will count as a syntax error, but it might.
ETA: ALSO! If you only want to update one record, the one with a specific ID (which I infer from your question text) you will need to specify that record ID in the WHERE clause.
If you records don't have unique IDs, you have a very big problem that you need to fix. A unique ID is absolutely required if you want to be able to update a specific record.
You will also need a properly format string expression for the date:
piv_SALED_DATE = #" + dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "# ,
and in Access SQL you will use "Select Top n .." to select the first n values.
Can someone help me with the problem that I'm having now?
I have a set of question(survey). When the user done the survey, it will insert to my database.
However, right now, when I submit the survey, it doesn't insert the result into my database.
here is my code:
try {
//Process - Query from SQL
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES"
+ " ('"+ member_ID + "', " + contact_num + ", '" + email_add + "', '" + mail_add + "' , " + radio_group + "," + receive_info + ")";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/customers", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSqlnsert);
I've also add in the library for the JDBC in the library folder.
It seems the non numeric values aren't quoted
Instead of
" + email_add + ",
try
'" + email_add + "',
In the below insert statement
INSERT INTO table (field1, field2) VALUES ( 5, 'this is a string');
the 'this is a string' is wrapped in quotes, because field2 is of type VARCHAR. field1 is INT so the value assigned to it (5) doesn't need quoting.
The VALUES list must be in braces too and again, non numeric values must be quoted:
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES (" + member_ID + ", " + contact_num + ", '" + email_add + "', '" + mail_add + "', '" + radio_group + "', '" + receive_info + "')";
Try to make a prepared statement where you can call setInt or setString method of preparedStatement class . so it will automatically remove string or numeric confusion at all.
BTW preparedStatement is the best way to pass parameter in sql query.don't use Statement class for parameter sql query.
I need help on what I am doing wrong, please.
database called renters
addressID is auto-increment from a table called Property, and included in a table called Renter, I am doing a java assignment.
I connect to the database, and when I try to add a new renter it gives me this error
Error processing the SQL!java.sql.SQLException: Field 'AddressID' doesn't have a default value
Database connection terminated
here is my insert statement:
String addFirstName = txtFirstName.getText();
String addLastName = txtLastName.getText();
String addCellPhone = txtCellPhone.getText();
String addDepositPaid = txtDepositPaid.getText();
String addDepositAmtPaid = txtDepositAmtPaid.getText();
Statement lstatement = conn.createStatement();
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid) VALUES('" + addFirstName + "','" + addLastName + "','" + addCellPhone + "','" + addDepositPaid + "'," + addDepositAmtPaid + ")";
myStatement.executeUpdate(ls_query); JOptionPane.showMessageDialog(null, "New Renter Added");
;
Have a look at the database schema, probably column AddressID is marked as NOT NULL. You're trying to insert a record without specifying a value for that column, and as there's no default value specified the insert fails.
So, you can either modify the schema and remove the NOT NULL constraint if that makes sense, OR specify a default value for that column, OR provide one with your insert.
But there is another in my opinion major issue with your code: as you are stringing together the insert statement you're wide open to SQL injections. The solution is quite simple, use PreparedStatement, a good tutorial can be found here
Head over to bobby-tables.com, it's a great first introduction to the very frequent problem of SQL injection with recipes on how to avoid them for many languages, including Java. A great resource!
Add AddressID when using Insert command. In general every non default column and non AutoIncrement column must be inserted.
Try
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid,AdressId) VALUES('" + addFirstName + "','" + addLastName + "','" + addCellPhone + "','" + addDepositPaid + "','" + addDepositAmtPaid + "','0')";
EDIT
Im not experienced in java. But looks like the ; works like in C#.
A INSERT statement usually ends or delimits with ; in other words in MySQL says execute from this point.
Can you give this a try?
ls_query = "INSERT INTO Renter (FirstName,LastName,CellPhone,DepositPaid,DepositAmtPaid,AdressId) VALUES('" + addFirstName + "','" + addLastName + "','" + addCellPhone + "','" + addDepositPaid + "','" + addDepositAmtPaid + "','0');";