I have this problem in C#, I have already run this query in SQL Server and works
SQL query
SELECT Mineria.dbo.Usuario.ID_Usuario, Mineria.dbo.Usuario.Sexo, Mineria.dbo.Usuario.Idioma, Mineria.dbo.Usuario.Edad, Mineria2.dbo.ARTISTA.Nombre_artistic
INTO Mineria.dbo.Objeto
FROM Mineria.dbo.Usuario
INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN 35 AND 70
ORDER BY ID_Usuario ASC
I can't find the problem on the c# code
SqlCommand comando = new SqlCommand(string.Format("
Select '" + maskedTextBox1.Text + "' , '" + maskedTextBox2.Text + "'
INTO Mineria.dbo.Objeto FROM Mineria.dbo.Usuario INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN '" + textBox1.Text + "' AND '" + textBox2.Text + "' ORDER BY ID_Usuario ASC"), cn);
It's probably because you're putting single-quotes around the field names (should be nothing since you're using fully-qualified names), and around the integers in the BETWEEN statement (should be nothing because they're numbers, not text):
SqlCommand comando = new SqlCommand(string.Format("
Select " + maskedTextBox1.Text + " , " + maskedTextBox2.Text + "
INTO Mineria.dbo.Objeto FROM Mineria.dbo.Usuario INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN " + textBox1.Text + " AND " + textBox2.Text + " ORDER BY ID_Usuario ASC"), cn);
Related
I am currently reading and parsing 10 different file(.txt, .csv), each file has a different number of columns.
Here is a sample from one file:
SqlCommand cmd = new SqlCommand("insert into " + table_name + " VALUES('"+data_from_file[0]+"', '" + data_from_file[1] + "', '" + data_from_file[2] + "', '" + data_from_file[3] + "', '" + data_from_file[4] + "','" + data_from_file[5] + "', '" + data_from_file[6] + "', '" + data_from_file[7] + "', '" + data_from_file[8] + "', '" + data_from_file[9] + "');", connection);
cmd.ExecuteNonQuery();
This file has a total of 10 columns that gets inserted into its own table. If I do it like this for the 10 files, I would have 10 different if/else if statements. And to me that sounds like bad way of doing this. Is there a way to iterate through the array and insert each element? I have been looking for ways to do it, but cannot find a proper solution for my problem. Thanks for the help.
The most classical way would be to iterate and append to a string and then execute:
string command = "insert into " + table_name + " VALUES(";
foreach(string data in data_from_file)
{
command += "'" + data + "',";
}
command = command.TrimEnd(','); // remove the last extra ','
command += ");";
SqlCommand cmd = new SqlCommand(command);
cmd.ExecuteNonQuery();
However, I recommend that you have a look at SqlBulkCopy for Large Insert Queries.
First you iterate over your collection, and then you insert every entry from the collection into the database.
foreach (var oneColumn in data)
{
SqlCommand cmd = new SqlCommand("INSERT INTO " + table_name + " VALUES(" + oneColumn + ")");
cmd.ExecuteNonQuery();
}
I need to update the details in a certain row of my SQL Server CE database as the user wants requires to. But I get an error
There was an error parsing the query.[Token line number=1,Token line offset=31,Token in error=Name]
My query is:
"Update MembersTable set First Name='" + txtFirstName.Text +
"', Surname='" + txtSurname.Text +
"', Middle Name='" + txtMiddleName.Text +
"',Home Address='" + txtAddress.Text +
"',Date Of Birth='" + dtpDOB.Text +
"',Home Phone No='" + txtHomePhone.Text +
"',Mobile No='" + txtMobilePhone.Text +
"',Email='" + txtEmail.Text +
"',Profession='" + txtProfession.Text +
"',Cell Leaders Name='" + txtCellLeader.Text +
"' Where ID='" + DC.ID + "'";"
What am I doing wrong??
It appears like your column names contain spaces.
To deal with this, you'd want to enclose the column name with square brackets [ ]
"Update MembersTable set [First Name]='" + txtFirstName.Text + "',Surname='" + txtSurname.Text + "',[Middle Name]='" // ...
I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.
I have data set that is being filled from sql query, like this
cmd_sql.CommandText = " SELECT BrDok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok);
Now I want to extract value from data set for sql update, like this one
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
I tried this ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] but I got an error,
I was thinking to do something like this
string BrDok;
BrDok = ds_dok.["BrDok"].ToString();
But nothing, how to extract that BrDok or just put it into procedure?
Thanks infront!
Make it
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok,"BrDok");
Then use
ds_dok.Tables["BrDok"].Rows[0]["BrDok"].ToString()
Try this
ds_dok.Tables[0].Rows[0]["BrDok"]
If you provide a string argument for the dataset class, then it will be the dataset name and not the datatable name. And there is no table in the database with name you provided for a dataset, so give it while filling the dataset. Write some thing like below.
DataSet ds_dok = new DataSet();
sql_adapter.Fill(ds_dok,"ordersstavke");
and you can write all the remaining code as it is in your code part.
And your second update query has some syntax error, see it like below
myQuery = "UPDATE ordersstavke " + "SET BrDok = '" + rw_mat["brdok"] + "', "
+ "SifParFil = '" + rw_mat["sifskl_kor"] + "', " + "WHERE BrDok
= '" + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
You forgot to put an starting inverted comma at the where clause.
Just a small hint to the sql-command. You should use sql-parameters to prefent sql-injection.
I have a windows service which inserts data into some tables. It does so fine when in debug mode, but when I install it says "Data type mismatch in criteria expression." for every insert.
query = "INSERT INTO printers (" +
"hostname," +
"ip_address," +
"model," +
"picture_id," +
"connect_type," +
"status," +
"product_number," +
"Floor_ID," +
"print_corner," +
"serial_number," +
"printer_features" +
") VALUES ('" +
exp.Devices[i].HostName.ToString() + "', '" +
exp.Devices[i].IpAddress.ToString() + "', '" +
exp.Devices[i].Model.ToString() + "', '" +
exp.Devices[i].PictureId.ToString() + "', '" +
exp.Devices[i].ConnectType.ToString() + "', '" +
exp.Devices[i].Status.ToString() + "', '" +
exp.Devices[i].ProductNumber.ToString() + "', '" +
exp.Devices[i].Floor.ToString() + "', '" +
exp.Devices[i].PrintCorner.ToString() + "', '" +
exp.Devices[i].SerialNumber.ToString() + "', '" +
exp.Devices[i].PrinterFeatures.ToString() +
"')";
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + confParams.MpaSearchDatabase;
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(query);
myCommand.Connection = conn;
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
insertedPrintersCount = insertedPrintersCount + 1;
Utils.Logger.Info("Device inserted: " + exp.Devices[i].HostName);
help!
The data type mismatch error indicates the query is expecting data of one type but you're providing another. This query expression is passing every value as a string literal but several columns indicate they are likely a numerical value. ProductNumber and SerialNumber for example.
In order to pass the values correctly (and prevent easy injection attacks) you'll want to use the OleDbCommand class to build up the call with values of the correct type. Then let the underlying infrastructure translate it to the appropriate values.