BLOB , Insert SQL Database - c#

I have an error that I can't fix ... I really don't know why .
I'm using this code tu upload a file in my database, i want to use the BLOB now .
if (FileUpload1.HasFile)
try
{
//FileUpload1.SaveAs("C:\\inetpub\\wwwroot\\ClientPortalCs\\"
//+ GetTheCurrentDirectory(MyTreeView.SelectedNode)
//+ "\\" + FileUpload1.FileName);
//LabelFile.Text = "File name: " +
//FileUpload1.PostedFile.FileName + "<br>" +
//FileUpload1.PostedFile.ContentLength + " kb<br>" +
//"Content type: " + FileUpload1.PostedFile.ContentType;
dbConnection.Open();
dynamic queryString = ("INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES ('"
+ FileUpload1.FileName + "','" + GetTheCurrentDirectory(MyTreeView.SelectedNode) + "','" + Request.Cookies["UserSettings"]["UserName"] + "','" + DateTime.Now + "','" + FileUpload1.FileBytes + "' );"
+ "SELECT CAST(scope_identity() AS int)");
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
int newFid = (Int32)theCommand1.ExecuteScalar();
dynamic queryStringFolder = ("INSERT INTO FILES_FOLDERS (Folder_Id,File_Id) VALUES ('"
+ MyTreeView.SelectedValue + "'," + "'" + newFid + "')");
theCommand1 = new SqlCommand(queryStringFolder, dbConnection);
theCommand1.ExecuteNonQuery();
dbConnection.Close();
}
In my database the field DATA in the table files is a varbinary(max) .
The parameter for DATA field in the query is the bytes of the file I try to upload .
The error occured is :
"Error Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. "
Can someone tell me why ?
Thank you very much .

The problem, I think, is that you are passing in the byte [] of your image as a string because you are enclosing it in single quotes.
Remove the single quotes around here:
'" + FileUpload1.FileBytes + "'"
One more recommendation: Use parameters for your queries. You'll save yourself from sql injection attacks, your queries may run faster and you'll eliminate this kind of mistakes in the future.
UPDATE - using parameters:
string queryString = "INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES (#Name,#Path,#UserUpload,#Date,#Data)";
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
theCommand1.Parameters.AddWithValue("#Name",FileUpload1.FileName);
theCommand1.Parameters.AddWithValue("#Path",GetTheCurrentDirectory(MyTreeView.SelectedNode));
theCommand1.Parameters.AddWithValue("#UserUpload",Request.Cookies["UserSettings"]["UserName"]);
theCommand1.Parameters.AddWithValue("#Data",FileUpload1.FileBytes);
theCommand1.Parameters.AddWithValue("#Date",DateTime.Now);
int newFid = (Int32)theCommand1.ExecuteScalar();

Related

C# Store Unknown Amount of Elements in SQL Table

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();
}

Syntax error in INSERT INTO statement MS access (not keyword issue)

I am facing this error when I try to insert a data row in to table in ms access file.
dataTable is table I got using select * from TableName,
I got it, displayed it, made changes, now I want to replace previous one with new one. So I am going to delete all previous rows and add each row one by one from new table. But I am not able to insert any row.
I am getting this error
"Syntax error in INSERT INTO statement."
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES (#TaskID,"
+ " #HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName, "
+ " #nFontInfo, #Keywords)";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
command.Parameters.AddWithValue("#TaskID", dataTable.Rows[0]["TaskID"]);
command.Parameters.AddWithValue("#HTMLTopic", dataTable.Rows[0]["HTMLTopic"]);
command.Parameters.AddWithValue("#Group", dataTable.Rows[0]["Group"]);
command.Parameters.AddWithValue("#nKey", dataTable.Rows[0]["nKey"]);
command.Parameters.AddWithValue("#nText", dataTable.Rows[0]["nText"]);
command.Parameters.AddWithValue("#nImage", dataTable.Rows[0]["nImage"]);
command.Parameters.AddWithValue("#nSelImage", dataTable.Rows[0]["nSelImage"]);
command.Parameters.AddWithValue("#nFontName", dataTable.Rows[0]["nFontName"]);
command.Parameters.AddWithValue("#nFontInfo", dataTable.Rows[0]["nFontInfo"]);
command.Parameters.AddWithValue("#Keywords", dataTable.Rows[0]["Keywords"]);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
Edit:
Changed it just for debugging to
String query = "INSERT INTO [" + TableName + "] (TaskID, HTMLTopic, nRelative, [Group], nKey,"
+ " nText, nImage, nSelImage, nFontName, nFontInfo, Keywords) VALUES ('" + dataTable.Rows[0]["TaskID"]
+ "', '" + dataTable.Rows[0]["HTMLTopic"] + "', '" + dataTable.Rows[0]["nRelative"] + "', '" + dataTable.Rows[0]["Group"]
+ "', " + dataTable.Rows[0]["nKey"] + ", '" + dataTable.Rows[0]["nText"] + "', '" + dataTable.Rows[0]["nImage"]
+ "', '" + dataTable.Rows[0]["nSelImage"] + "', '" + dataTable.Rows[0]["nFontName"] + "', '" + dataTable.Rows[0]["nFontInfo"]
+ "', '" + dataTable.Rows[0]["Keywords"] + "')";
OleDbCommand command = new OleDbCommand(query, mdbConnection);
Debug.Print(command.CommandText);
mdbConnection.Open();
command.ExecuteNonQuery();
mdbConnection.Close();
I added some single quotes so database can understand them as string.
There looks to be a bug somewhere between the provider and the engine. It looks like the issue is with your column named nText.
I duplicated your schema in an Access 2013 db and received the same error that you did. I then started making various changes to the column names and the query. When I changed column names (appending a X to the end of each column) the INSERT worked. I then went back and started adding square brackets to other columns names. As soon as I did that for nText it worked. This query works for me in a C# console app using the Microsoft.ACE.OLEDB.12.0 oldeb provider:
String query =
"INSERT INTO [" + TableName + "] (TaskID,HTMLTopic,[Group],nKey,[nText],nImage,nSelImage,nFontName,nFontInfo,Keywords)" +
"VALUES" +
"(#TaskID,#HTMLTopic, #Group, #nKey, #nText, #nImage, #nSelImage, #nFontName,#nFontInfo, #Keywords)"
I agree with you that it shouldn't be a keyword / reserved word issue, but it sure acts like it is. NTEXT is a keyword in TSQL (SQL Server), but not Access according to https://support.microsoft.com/en-us/kb/286335.

Data type mismatch in criteria expression Oledb Access database

I'm getting the error:
Data type mismatch in criteria expression
When using this code. And using Access database.
OleDbConnection bab = new OleDbConnection();
bab.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";
bab.Open();
try
{
OleDbCommand kaas = new OleDbCommand();
kaas.Connection = bab;
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "') ";
kaas.ExecuteNonQuery(); // this is where it goes wrong
txtStatus.BackColor = Color.Green;
MessageBox.Show("data saved");
bab.Close();
}
catch (Exception ghakbal)
{
MessageBox.Show("Error" + ghakbal);
}
You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:
'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...
Also It would be better to specify the type directly and use the Value property. Read more here.

Read Data from data set

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.

Data type mismatch in criteria expression

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.

Categories

Resources