hey I have two tables and Im looking to make a mysql sytax statement for insert:
Table structure:
Im trying to insert userid and picturepath (which i can do) but how would I insert into flag in the user table aswell in the same insert syntax:
("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "')", cn);
theuserid is set by a session so I can reuse the string for that to know which coloum to insert into the user.
gonna have to do an update statment after the insert statement
("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "') "+
"GO UPDATE user SET flag = 1 WHERE UserID = "+theUserId+" GO", cn);
might work
try to execute this command in sql management if you have it with test data to make sure it allows this to work like this
Related
This is my C# code - I am running the query
INSERT INTO PM
VALUES ('Ali', '6777777', '3', 'Batsman', 'Fine Player', 'njhuh8obj', 'Lahore');
It is running fine in the database, but not this.
protected void btnAdd_Click(object sender, EventArgs e)//button that add players
{
// for picture to be uploaded
string path = "~/Admin/Players" FileUploadPicture.FileName;
FileUploadPicture.SaveAs(Server.MapPath(path));
SqlCommand cmd = new SqlCommand("INSERT INTO PM VALUES ( '" + TxtPlayerName.Text + "','"+TxtPlayerType.Text + "','" + TxtPlayerBasePrice.Text + "','" + TxtPlayerRecord.Text + "',
'" + ddlCat.SelectedItem.Value + "','" + path + "','" + TxtPlayerAddress.Text + "')", con);//Query of my C# page
// open connection with database
con.Open();
// Command for running query
cmd.ExecuteNonQuery();
con.Close();
// message shown after player is added
Response.Write("<script>alert('**Player Added**')</script>");
}
It seems that there is a problem in code of my C# page not in database, but I am not sure about that.
So please help me to solve this out...
It looks like the second column of your database table accepts an integer value but you are passing a string (TxtPlayerType.Text). If you want to insert an entry with only values for select columns you must specify the column names as follows:
INSERT INTO table_name (Column1, Column2, ...) VALUES (Value1, Value2, ...)
When Column Names aren't specified you must pass values in the order they appear in the database table.
Insert statement should follow the below format
Insert into <TableName>(Column1,Column2) Values (Value1,Value2)
It is good practice to define the column names in the statement as it make sure the order of the columns and also in future if new column added or deleted no need to change the code
MySqlCommand cmd1 =
new MySqlCommand(
"INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "' , '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')", conn);
{
Can I get some help please? Im getting Column count doesn't match value count at row 1 when the command1 is executed.
You should never use SQLs like this. It is prone to SQL Injection attacks. When you use it like yours, one can steal confidential information from database or even delete your tables, data etc. For details please read SQL Injection on wiki
Instead you should use parameterized SQL queries. In that way you are safe from injection attacks and I believe it is much more practical to write sql.
In your case entering single ' char into one of the textboxes will cause your query to get exception. To fix the issue just use prameters.
For your case you can write something like that.
string sqlString = #"INSERT INTO quotedetails (
name,
address,
district,
date,
forto,
refto,
total)
VALUES (
#PAR_name,
#PAR_address,
#PAR_district,
#PAR_date,
#PAR_forto,
#PAR_refto,
#PAR_total)";
MySqlCommand cmd1 = new MySqlCommand(sqlString, conn);
cmd1.Parameters.AddWithValue("PAR_name", txttoname.Text);
cmd1.Parameters.AddWithValue("PAR_address", txttoaddress.Text.Replace("\r\n", "<br />"));
cmd1.Parameters.AddWithValue("PAR_district", txtdistrict.Text);
cmd1.Parameters.AddWithValue("PAR_date", dateTimePicker1.Value.Date);
cmd1.Parameters.AddWithValue("PAR_forto", txtfor.Text);
cmd1.Parameters.AddWithValue("PAR_refto", txtref.Text);
cmd1.Parameters.AddWithValue("PAR_total", txttotal.Text);
Please note that I use prefix PAR_ for my sql parameters, it is just a convention you can use that or skip PAR_ prefix does not matter and it is all about naming habits.
Additionaly; in a parameterized query, you don't need to convert all your values to string. You can use DateTime for your date field or you can pass int variable without using ToString() as you do before.
On the face of it, this happens when the number of values are more or less than columns provided.
From your statement, this does not seem to be the case. BUT since you are providing uielements directly into insert statement (Textbook case of SQL Injection), I am guessing there is a single quote ' in any of your ui elements, which breaks your insert statement.
MySqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "', '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')";
Using SQL parameters will save you from lots of trouble as well as SQL injection.I am quite sure that if you use parameters your problem will be resolved:
MySqlCommand cmd1 = new MySqlCommand( "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES(#name,#address,#district,#date,#forto,#refto,#total)", conn);
cmd1.Parameters.AddWithValue("#name",txttoname.Text);
cmd1.Parameters.AddWithValue("#address",+ txttoaddress.Text.Replace("\r\n", "<br />").ToString());
cmd1.Parameters.AddWithValue("#district",txtdistrict.Text);
...
Starting to learn sql and having trouble with my query. I have - 2 tables calendar and activities and FK table DateActivities. Got 2 simple lists calendar with dates and activities. I want to be able with a button click to enter new activity through text box on selected date. But when I do that I get error on a query. Thanks for your help.
private void btnAddToDate_Click(object sender, EventArgs e)
{
string query = "DECLARE #ActivitiesId TABLE (Id INT) " +
"INSERT INTO Activities (Name) " +
"OUTPUT INSERTED.ID INTO #ActivitiesId Id(Id) " +
"VALUES (#ActivitiesName) " +
"INSERT INTO DateActivities VALUES (#CalendarId, #ActivitiesId)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#ActivitiesName", textDate.Text);
command.Parameters.AddWithValue("#CalendarId", listCalendar.SelectedValue);
command.ExecuteNonQuery();
}
FillCalendar();
FillActivities();
}
You are trying to execute multiple statement and thus need to separate them with ; as line terminator like below else it's treated as single statement to execute. If you just copy/paste the statement block in SSMS you will get the same error.
"DECLARE #ActivitiesId TABLE (Id INT); " +
"INSERT INTO Activities (Name) " +
"OUTPUT INSERTED.ID INTO #ActivitiesId Id(Id) " +
"VALUES (#ActivitiesName); " +
"INSERT INTO DateActivities VALUES (#CalendarId, #ActivitiesId)"
You should better pull this off to a stored procedure instead running as adhoc query.
You are inserting whole table in the column value of DateActivities which is obviously wrong and will fail, you need to use another variable to hold the ActivityId and then insert it next, see below:
"DECLARE #ActivitiesId TABLE (Id INT)
DECLARE #ActivityId INT " +
"INSERT INTO Activities (Name) " +
"OUTPUT INSERTED.ID INTO #ActivitiesId Id(Id) " +
"VALUES (#ActivitiesName) " +
"SELECT #ActivityId = Id from #ActivitiesId"
"INSERT INTO DateActivities VALUES (#CalendarId, #ActivityId)";
I am trying to insert a record to a mysql database using c# but I always saw this error message:
You have error in your SQL syntax;check the manual that corredponds to
your MySQL server version for the right syntax to use near
'Order(idOrder, Quantity, Date, Menu_idMenu)VALUES(10002,
'1', '3/17/2013 12:00' at line 1
this is the code:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
com.CommandText = "INSERT INTO Order (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
int insert = com.ExecuteNonQuery();
}
}
what does it mean?
You have reserved keywords in your query, Order. Quote it and be happy.
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
Also, it is good practice to use parameters.
Date and Order are reserved keywords on MySQL.
Use them between ''
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (" + 10002 + ", '" +row.Cells[0].Value.ToString() + "', '"+DateTime.Today.ToString()+"', '" + row.Cells[1].Value.ToString() + "')";
And always use parameterized queries. This kind of codes open for an SQL Injection attacks.
Actually, you can use Date without quotes.
MySQL permits some keywords to be used as unquoted identifiers because
many people previously used them.
Since, I suggest you using parameterized queries, here how you can use it with your code;
com.CommandText = "INSERT INTO `Order` (idOrder, Quantity, Date, Menu_idMenu) VALUES (#idOrder, #Quantity, #Date, #Menu_idMenu)";
com.Parameters.AddWithValue("#idOrder", "10002");
com.Parameters.AddWithValue("#Quantity", row.Cells[0].Value.ToString());
com.Parameters.AddWithValue("#Date", DateTime.Today.ToString());
com.Parameters.AddWithValue("#Menu_idMenu", row.Cells[1].Value.ToString());
I have an app that displays data from a sql database in a datagrid. I am adding a feature that will allow a user to add a new item to this datagrid. I will have an Add button in the app that when clicked, will open a new window where all the info will be added. After the user inputs the info into the text boxes and clicks save, that info gets saved to the database. This will require inserting data into two separate tables that are related. The first table is ItemDescriptor and the other table is Accessories. The id for ItemDescriptor has to be put into the Accessories table as ItemDescriptorID. I have tried to do two separate insert queries but cant figure out how to get the id from ItemDescriptor into the Accessories table programatically. Sorry, I know this might be a little confusing. Let me know if more info is needed. Thanks
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + System.Guid.NewGuid() + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" +
and thats about as far as i got...not sure how to get the ItemDescriptorID in there from the first query.
First, please please please use parameterized queries when dealing with user-supplied input. That string concatenation stuff is just asking for a SQL injection attack.
Second of all, if you're using SQL Server, you can use something like ##IDENTITY to get the identity field after insertion. There's something comparable on all systems, so if you let us know what you're using we can point you in the right direction.
I'm assuming that you're using SQL Server and that ItemDescriptor.id is an identity column; correct?
If you execute the following command immediately after your initial insert statement, it will return the value of the most recently generated identity:
var newID = _dbAccess.ExecuteScalar("SELECT Scope_Identity()");
You can use newID to construct your second insert statement.
One caveat: The SELECT Scope_Identity() statement must be executed on the same connection instance as the initial insert statement. So ensure that you're not closing and reopening your connection between statements. If this seems to be a problem, you can actually combine your insert and select statements into a single command; e.g.:
var newID = _dbAccess.ExecuteScalar("INSERT [all your code here]; SELECT Scope_Identity();");
Good luck!
Check out this site about Getting the identity of the most recently added record
I figured out a way to make it work. I just made the guid an object and then used it as a variable and that worked. thanks for all the suggestions.
Guid guid = System.Guid.NewGuid();
if (_dbaccess != null)
{
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + guid + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" + guid + "', '" + tbStorageRoom.Text + "', '" + tbOnHand.Text + "', '" + tbHiBay.Text + "')");
}