Case: I'm trying execute a query in C# with MySql.Data.MySqlClient, which containts INSERT INTO, i'm getting an error(see below):
Database table:
What im trying to achieve: I want to insert into a new record with: "value_id(Auto Increment)", "machine_id" "tag_name", "int_value", "real_value" and "bool_value";
I have the following code:
*Retrieving machine ID
private void getMachineID()
{
string connStr = "";
string ipAdressID = "'" + machineIP + "'";
string basicQueryID = "SELECT machine_id FROM machine WHERE machine.machine_ip LIKE ";
string totalQueryID = basicQueryID + ipAdressID;
//Create connection
MySqlConnection conn = new MySqlConnection(connStr);
//Query command
MySqlCommand cmd = conn.CreateCommand();
//Assign string to query
cmd.CommandText = totalQueryID;
//Open connection
conn.Open();
//Get result ID from machine where IP adress = machineIP and write to machineID variable.
machineID = (int)(cmd.ExecuteScalar());
}
Code to insert into the record:
try
{
string connStr = "";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO waardes(machine_id, tag_name, int_value, real_value, bool_value) VALUES(#machineID, #tagName, #intValue, #doubleValue, #boolValue)";
cmd.Parameters.AddWithValue("#tagName", tagName);
cmd.Parameters.AddWithValue("#intValue", intValue);
cmd.Parameters.AddWithValue("#doubleValue", doubleValue);
cmd.Parameters.AddWithValue("#boolValue", boolValue);
cmd.Parameters.AddWithValue("#machineID", machineID);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Hope you guys can help!
There's no INSERT with where clause.
Take a look at this question: How to insert with where clause
Maybe, you can create an IF inside your app to verify your parameters before executing the INSERT statement.
Based on your query, I believe you need an UPDATE:
UPDATE waardes SET tag_name = #tagName,
int_value = #intValue, real_value = #doubleValue,
bool_value = #boolValue WHERE machine.machine_id LIKE %1%
Is this what you need?
you cannot use where in insert statement, because insert statement is used for adding new rows to table. you better use update statement.
There can be no Where clause used with Insert. However you can use Where when you are using Insert Into. In your statement I suppose you are missing the Select From before your Where clause.
Consider the example:
INSERT INTO tableNameDestination
SELECT feild(s),...
FROM tableNameSource
WHERE Condition
In your case:
INSERT INTO waardes(tag_name, int_value, real_value, bool_value) VALUES(#tagName, #intValue, #doubleValue, #boolValue) Select field1, field2, field3, field4 from machine WHERE machine.machine_id LIKE " + "'" + machineID + "'";
*sorry the title cannot be too long so I have to cut it down.
hi, I would like to get the total duration from my database table where the
dateID is 1 and the year of the datetime is 2016 using SQL Query in asp.net c#. I tried using the codes below but it does not work. It says 'Additional information: Column 'RecordsDate.StartDateTime' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.' Can anyone tell me what's wrong with my SQL Query please? Thanks a lot :)
float totalDuration = 0f;
string sQuery = "SELECT sum(Duration) AS TotalDuration FROM RecordsDate WHERE DateID='1' HAVING DATEPART(yyyy, StartDateTime) = '2016'";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(sQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
totalDuration = float.Parse(dr["TotalDuration"].ToString());
}
conn.Close();
dr.Close();
Provide group by with some column name from the table:
select sum(duration) as totalduration from recordsdate
where dateid='1' having datepart(yyyy, startdatetime) = '2016'
group by ?
I have the following code:
SqlConnection c = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=BookStoreDataBase1;Integrated Security=True;Pooling=False;");
c.Open();
string raf = string.Format("Select Id from Customer WHERE email='{0}'", DropDownList1.SelectedItem.Text);
SqlCommand comm2 = new SqlCommand(raf, c);
SqlDataReader r = comm2.ExecuteReader();
The object r now has the value of the query which is a row contains that the Id where email equals to random value from drop down list.
what I want is to get the exact value of that "Id" and assign it to label. please help me.
First of all your query is open to SQL Injection attack so change it like this:-
string raf = "Select Id from Customer WHERE email= #Email";
SqlCommand comm2 = new SqlCommand(raf, c);
cmoo2.Parameters.Add("#Email",SqlDbType.NVarchar,20).Value =
DropDownList1.SelectedItem.Text;
You are fetching just one value so it can be done use ExecuteScalar like this:-
labelid.Text= cmoo2.ExecuteScalar.ToString();
But If you want to use SqlDataReader object then it will return the value when you call the Read method:-
using(SqlDataReader reader= cmoo2.ExecuteReader())
{
while (reader.Read())
{
labelid.Text= reader["Id"].ToString();
}
}
There are lot of examples already in stack overflow regarding this topic you can refer any of that answers or try this
using(SqlDataReader r= cmd.ExecuteReader())
{
while (r.Read())
{
var myString = r.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
labelid.Text=myString;
}
}
I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";
I have inserted values into sql several times but now i am facing problem with the following code
protected void Button1_Click(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con = new SqlConnection(connstring);
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone=Convert.ToInt64(txtPhone.Text);
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
string insertstring = " insert into JobRegisteration values ("+name+","+user+","+password+","+email+","+phone+","+address+","+city+","+gender+","+dob+","+qualification+","+skills+")";
cmd = new SqlCommand(insertstring,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
When I am inserting values into this through asp.net page, its giving following error.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'sbip'.
Invalid column name 'tttt'.
Invalid column name 'ttt'.
The multi-part identifier "tttttt#sss.ss" could not be bound.
Invalid column name 't'.
Invalid column name 'tttt'.
Invalid column name 'Male'.
Invalid column name 'MCA'.
Invalid column name 'C#'.
where tttt, male mca, etc etc are values that are passed from asp page.
thanks!
use parameters like below and also using statements
string connstring = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
// change this select statement based on your exact column names
string insertstring = "insert into JobRegisteration ([Name] ,[User] ,[Password] ,[Email] ,[Phone],[Address] ,[City] ,[Gender] ,[Dob] ,[Qualification] ,[Skills]) values (#name ,#user ,#password ,#email ,#phone,#address ,#city ,#gender ,#dob ,#qualification ,#skills)";
using (var con = new SqlConnection(connstring))
using(var cmd = new SqlCommand(insertstring, con))
{
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#user", txtUser.Text);
// give all the parameters..
con.Open();
cmd.ExecuteNonQuery();
}
You need to wrap your inserted values with ' otherwise the database treat them as column names:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
Also, as other suggested you really should rely on Prepared Statements to avoid such problems (among others).
There are many solution to your problem.
1) Try to fit with this format:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
2) as said haim770, surround your values with '
3) use sql parameters way
4) or look at Linq, that's really simplify way to work with database
You need to add single quote ' in your query:
string insertstring = " insert into JobRegisteration values ('"+name+"','"+user+"','"+password+"','"+email+"','"+phone+"','"+address+"','"+city+"','"+gender+"','"+dob+"','"+qualification+"','"+skills+"')";
use using (pun!), bind variables (a.k.a. parameters), format your query, when query seems dubious put what you want explicitly...
protected void Button1_Click(object sender, EventArgs e) {
string name = txtName.Text;
string user = txtUser.Text;
string password = txtPwd.Text;
string email = txtEmail.Text;
long phone = Convert.ToInt64(txtPhone.Text); // <- what about +77(555)123-456-78?
string address = txtAddr.Text;
string city = txtCity.Text;
string gender = RadioButtonList1.SelectedItem.ToString();
string dob = txtDOB.Text;
string qualification = DropDownList1.SelectedItem.ToString();
string skills = CheckBoxList1.SelectedItem.ToString();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString)) {
con.Open();
using(var cmd = con.CreateCommand()) {
cmd.CommandText =
// replace all "field_for_*" for actual fields
#"insert into JobRegisteration(
field_for_name,
field_for_user,
field_for_password,
field_for_email,
field_for_phone,
field_for_address,
field_for_city,
field_for_gender,
field_for_dob,
field_for_qualification,
field_for_skills)
values (
#prm_name,
#prm_user,
#prm_password,
#prm_email,
#prm_phone,
#prm_address,
#prm_city,
#prm_gender,
#prm_dob,
#prm_qualification,
#prm_skills)";
cmd.Parameters.AddWithValue("#prm_name", name);
cmd.Parameters.AddWithValue("#prm_user", user);
cmd.Parameters.AddWithValue("#prm_password", password);
cmd.Parameters.AddWithValue("#prm_email", email);
cmd.Parameters.AddWithValue("#prm_phone", phone);
cmd.Parameters.AddWithValue("#prm_address", address);
cmd.Parameters.AddWithValue("#prm_city", city);
cmd.Parameters.AddWithValue("#prm_gender", gender);
cmd.Parameters.AddWithValue("#prm_dob", dob);
cmd.Parameters.AddWithValue("#prm_qualification", qualification);
cmd.Parameters.AddWithValue("#prm_skills", skills);
cmd.ExecuteNonQuery();
}
}
}