MySql command "load data infile" execution error in C# - c#

I am trying to import a text file into MySql database using C# code but getting errors.
My table structure is:
and the C# code that I'm executing is:
fileQuery =
"load data infile '{0}' into table dgl.deliveries fields terminated by '\t' lines terminated by \r\n' (#ImagePath, Delivery_Note, Shipment_Number, #Delivery_Date, Deliver_To_Code, Deliver_To_Name, Sold_To_Code, Sold_To_Name, Material_Number, Doctype) set Delivery_Date = tr_to_date(#Delivery_Date, '%d/%m/%Y'), ImagePath = Concat('USERFILES/', #ImagePath)";
string q = string.Format(fileQuery,fileName);
MySqlConnection conn = new MySqlConnection(dglConnection.ConnectionString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = q;
conn.Open();
command.ExecuteNonQuery();
and the error is:
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.DLL but was not handled in user code
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%d/%m/%Y'), ImagePath = Concat('USERFILES/', #ImagePath)' at line 2
The following is a line from source input file:
123.pdf 802661341 1061611 18/02/2015 00:00:00 22280 ABC LIMITED 22280 XYZ LIMITED 30679795 30744488 DELIVERY NOTE 1

Your problem is that Your Date that you are passing from your C# code is 18/02/2015. Mysql only excepts a date in the format YYYY-MM-DD. You need to adjust that data so that it formats to the way Mysql will except a date if you want to store it as a date.
I actually wrote a stored procedure that you maybe able to use (or at least get an idea of what needs to be done): Here is the link.
Also when in doubt just refer to dev.mysql its a great resource also.

Related

Sending time to SQL Server Management Studio table but it does not display?

I am currently writing an application which involves a user being able to write the time to a database by clicking a button. The problem is that the data will be send to the database table, but it does not show the time in SQL Server Management Studio.
This is my query:
{
string query = "insert into Sign_In_Out_Table(Sign_In)Values('"+ timetickerlbl.ToString()+ "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#SignIn", DateTime.Parse (timetickerlbl.Text));
//cmd.ExecuteNonQuery();
MessageBox.Show("Signed in sucessfully" +timetickerlbl);
con.Close();
}
The datatype in SQL Server is set to datetime.
I'm open for suggestions to find a better way to capture the PC's time and logging it in a database.
Don't wrap the variable in ' when you are setting value with Parameters.Add(), or Parameters.AddWithValue() as they would wrap if needed.
The variable in here would be the value of Sign_In and not the Sign_In itself.
Always use Parameters.Add() instead of Parameters.AddWithValue():
string query = "insert into Sign_In_Out_Table(Sign_In) Values(#value)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#value", SqlDbType.DateTime).Value = DateTime.Parse(timetickerlbl.Text);
Edit (Considering your comment):
If still it does not insert it, of course there is an error in your code, it could be a syntax error, invalid table or column name, connection problem ,... so put your code in a try-catch block (if it isn't already) and see what error you you get, it should give you a hint:
try
{
//the lines of code for insert
}
catch(Exception ex)
{
string msg = ex.Message;
// the above line you put a break point and see if it reaches to the break point, and what the error message is.
}
Your table does not contain your timestamp because you have commented the execution of your query. Presumably you added the comment because this line was throwing an error, remove the comment and share the error with us.
cmd.ExecuteNonQuery();

Load data infile parameter error

LOAD data LOCAL INFILE
'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/amazon1.xml'
INTO TABLE
amazonxmlfeeddata
CHARACTER SET 'utf8'
LINES STARTING BY '<item_data>' TERMINATED BY '</item_data>'
(#tmp)
SET
item_unique_id = ExtractValue(#tmp, '//item_unique_id'),
item_title = ExtractValue(#tmp, '//item_title'),
item_long_desc = ExtractValue(#tmp, '//item_long_desc'),
item_page_url = ExtractValue(#tmp, '//item_page_url');
This is basically my query and I wrote this is in ASP.NET C#.
I want to execute this through C# in MySQL.
But if I execute through C# it gives me error of (#tmp) that it should be declared. And even after declaring it still throws the same error.
It seems you need to add AllowUserVariables=true; to the MySql connection string, to allow user variables (#tmp).
See: https://dev.mysql.com/doc/connector-net/en/connector-net-connection-options.html

Conversion failed in SQL procedure while executing from C#

I have a SQL stored procedure which uses openrowset command and fetches values from an excel sheet and inserts it into the database.
I have created a C# application which will call the procedure and execute it.
PROBLEM!
When I execute the procedure from SQL management studio, there are no errors. It happens perfectly. But when I execute it through the C# application I get an error: "Conversion failed when converting date and/or time from character string."
Code
SQL Query (only the insert part)
insert into tbl_item ([Item code],[Dt Created])
select[Item code] ,
case when [Dt Created] is null or [Dt Created]='' then null when ISDATE(CONVERT(nvarchar,CONVERT(datetime, [Dt Created],103))) =1 then CONVERT(datetime, [Dt Created],103) else null end as [Dt Created]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0; Database=C:\Upload\Report.xlsx;HDR=YES;IMEX=1;',
'select * from [Sheet1$]')
C# Code
public int updateItem()
{
SqlCommand cmd; cmd = new SqlCommand("usp_updateItem", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
try
{
if (conn.State.Equals(ConnectionState.Closed))
conn.Open();
cmd.ExecuteNonQuery();
ret = Convert.ToInt32(returnParameter.Value);
}
catch (Exception e)
{
err = "Error: " + e.Message;
return -1;
}
finally
{
conn.Close();
}
return ret;
}
What is the format you are having in the [Dt Created] variable.
the convert statement you have in the case will convert only the following types below
YYYY-MM-DD
YYYY-DD-MM
DD-MM-YYYY
The error you are getting is since you have a date in the format of "MM-DD-YYYY" something like '12-24-2015'. Due to this you are getting the conversion error.
Excuse me I want to stop you here. Your problem has resolved now but whatever
Karthik Venkatraman had said is correct. Somehow you got solution but for learning purpose i recommended to investigate little bit more. This is not belongs to the whatever you have said but damm sure this belongs to date-format.
**
One trick
Create one DateTimeVariable and once its initialized then just parse it using DateTimeParse class according to the records exist in database.
I am sure you will get solution.. Thanks :)
This is how I finally solved it...
The SQL error message 'Failed Conversion' was absolutely a wrong pointer. It had no connection to the issue at hand. [If only I knew this before :( ]
The actual problem was that I had called another procedure within the main procedure I had posted above. This setup ran perfectly in SQL management studio which was running under my credentials. Now in the C# application, I had created another SQL login user ID to run it. And this user ID did not have execute permission to run the sub procedure. And ironically, SQL gave me a misleading conversion error. Once I gave the right permission it worked perfectly.

Unspecified Error when trying to ExecuteReader on SQL Server CE

I had implemented a database storage on my app for Windows Mobile 6.5 using SQL Server CE.
Had managed to install the SQL Server CE CAB file on the device (Motorola MC65).
Managed to create database file, and create tables. Insert also can be executed.
However when I try to run ExecuteReader() to read records, I hit the following error:
Error Code: 80004005
Message : Unspecified error
Minor Err.: 25534
Source : SQL Server Compact ADO.NET Data Provider
No idea why this is happening. Since insert can be executed I thought this should not be a connection or privilege issue.
The reading code is as below:
openConnection();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT NAME FROM GROUP_INFO ORDER BY NAME ";
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string groupName = reader.GetString(0);
listGroup.Add(groupName);
}
The exception is thrown on the line where cmd.ExecuteReader() is executing.
Any pointers are appreciated. Thanks.
Implement proper error handling for SqlCeExceptions! The error is documented here https://technet.microsoft.com/en-us/library/ms172350(v=sql.110).aspx
Large objects (ntext and image) cannot be used in ORDER BY clauses.
Maybe you should redefine the column as nvarchar(4000) (it is currently ntext), or rephrase the query using:
ORDER BY CAST(Name as nvarchar(4000))
But this will cause a table scan

Sql insert command in C#

I'm currently creating a small C# program that inserts data from files into a postgres table.
The code that does the insertion looks like this:
NpgsqlCommand cmd = new NpgsqlCommand(#"INSERT INTO :table(text) VALUES (:word);", con);
cmd.Parameters.AddWithValue("table", table);
cmd.Parameters.AddWithValue("word", line);
cmd.ExecuteNonQuery();
But every time it tries to execute the "ExecuteNonquery" line I get the following error:
An unhandled exception of type 'Npgsql.NpgsqlException' occurred in Npgsql.dll
Additional information: ERROR: 42601: syntax error at or near "("
I can connect to the database I have checked. The variables table and line also have the correct values at runtime. I just can't figure out what the problem is..
Any suggestions ?
As far as I know the table can't be a parameter.
What you can do however is use string concatting/formatting for that:
string table = "table";
NpgsqlCommand cmd = new NpgsqlCommand(string.Format(#"INSERT INTO {0}(text) VALUES (:word);", table), con);
Guess that would work (didn't test it).

Categories