I'm attempting to read a file in to the database that I have, but I'm receiving the above mentioned error. After checking to make sure that all the information was correct (i.e. nothing trying to be put into the database that doesn't have a column and such) I sill receive the error. Next I ran it my mysqlworkbench and it works fine. Now I'm not sure where to go to next I can't check the error any deeper considering its throwing on the ExecuteNonQuery. The file that I'm importing is 3000 lines. When I shorten the file it succeeded. I guess the first question is to ask is there some sort of max connection time and if so do I need to shorten my file or lengthen the time it can stay connected? Any advice would be great, thanks. Also I use the ,, to terminate the fields because some of the data can have a , in it.
public void sendQuery(string filePath, int month)
{
conn.Open();
string monthName;
monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month);
monthName = monthName.ToLower();
monthName = monthName.Substring(0, 3);
try
{
command.CommandText = "SET SQL_SAFE_UPDATES = 0;" +
"load data local infile 'C:/Users/mem-joshuad/Desktop/temp.txt' into table "+monthName+" fields terminated by ',,' lines terminated by '\r\n'";
command.ExecuteNonQuery();
}
catch (MySqlException ex)
{
ScreenNavigation n = new ScreenNavigation();
n.homeScreen(ex.Message);
}
conn.Close();
}
All I needed to do was lengthen the default time out. See comments for the process.
Related
I got a web service running on c# but recently, something strange happened. Even when I query from a simple table with only 1 value like this:
string str = "";
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionStringTD"]))
{
connection.Open();
try
{
SqlCommand selectCommand = new SqlCommand
{
CommandType = CommandType.Text,
Connection = connection,
CommandText = "select Version from TN_Version"
};
str = selectCommand.ExecuteScalar().ToString();
}
catch (Exception exception)
{
str = "ERROR:" + exception.Message + "_" + exception.InnerException.Message;
Console.WriteLine(exception.Message ?? "");
}
return str;
}
This always returns correct value when I debug on local but an error message returned whenever I publish this service on host and execute it:
There is no row at position 0.
It's really strange cuz this is a simple table and absolute nothing changes or delete its value...
Error
And I have to execute the service 3 or 4 times until it gets me the correct value:
<string xmlns="http://webservice.com/">6.7</string>
Please, someone helps me, this have been bugging me to no end. Thanks you so much (really)
The error message simply means that no rows were returned by your query. so maybe, after you hosted the app, either IIS or a firewall causing this problem in the connection. Check with the firewall turned off and check the rights of your IIS user account.
I have a quite large dataset (900K records, 140Mb disk space) stored in CSV file in a client app (.NET 4.0). I need to load this data to Postgres 9 db the fastest way. I use Npgsql "NpgsqlCopyIn" technique (Npgsql library version=2.1.0).
For a probe load (138K) insertion works fine - it takes about 7 secons.
But for the whole batch (900K), the code throws timeout exception:
"ERROR: 57014: canceling statement due to statement timeout"
The stack trace is:
Npgsql.NpgsqlState.d_9.MoveNext() at
Npgsql.NpgsqlState.ProcessAndDiscardBackendResponses(NpgsqlConnector
context) at Npgsql.NpgsqlCopyInState.SendCopyDone(NpgsqlConnector
context) at Npgsql.NpgsqlCopyInState.StartCopy(NpgsqlConnector
context, NpgsqlCopyFormat copyFormat) at
Npgsql.NpgsqlState.d_9.MoveNext() at
Npgsql.NpgsqlState.ProcessAndDiscardBackendResponses(NpgsqlConnector
context) at
Npgsql.NpgsqlConnector.ProcessAndDiscardBackendResponses() at
Npgsql.NpgsqlCommand.ExecuteBlind() at Npgsql.NpgsqlCopyIn.Start()
I tried setting CommandTimeout to kilo values(>7200), zero; tried same values for connection "Timeout" parameter. Also I was trying to set "CommandTimeout" via connection string, but still with no result - "ERROR 57014" comes out again and again.
Please, help to load the batch correctly!
Here is the code I use:
private static void pgBulkCopy(string connection_string, FileInfo fiDataFile)
{
using (Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(connection_string))
{
con.Open();
FileStream ifs = new FileStream(fiDataFile.FullName, FileMode.Open, FileAccess.Read);
string queryString = "COPY schm.Addresses(FullAddress,lat,lon) FROM STDIN;";
NpgsqlCommand cmd = new NpgsqlCommand(queryString, con);
cmd.CommandTimeout = 7200; //7200sec, 120 min, 2 hours
NpgsqlCopyIn copyIn = new NpgsqlCopyIn(cmd, con, ifs);
try{
copyIn.Start();
copyIn.End();
}catch(Exception ex)
{
Console.WriteLine("[DB] pgBulkCopy error: " + ex.Message );
}
finally
{
con.Close();
}
}
}
Npgsql has a bug regarding command timeout and NpgsqlCopyIn handling.
You may test our current master where we had a lot of fixes about command timeout handling.
You can download a copy of the project in our GitHub page: https://github.com/npgsql/Npgsql/archive/master.zip
Please, give it a try and let us know if it works for you.
I am Beginner for Development and i am creating exe file to execute the SQL scripts. I have 3 doubts here.
1. How to get the file name from the folder at run time. (Currently i did hardcore)
2. How to write a log file after executed the query.
3. How to show alert message after executed the query? (Patch executed successful / Patch execution failed)
Please find my script mentioned below;
var txtconn = File.ReadAllText(#"C:\Users\Patch\Connstrng.txt");
var txtfile = File.ReadAllText(#"C:Users\Patch\Script.txt");
string[] sqlqry = txtfile.Split(new[] {"~GO~"}, StringSplitOptions.RemoveEmptyEntries);
var conn = new SqlConnection(txtconn);
var cmd = new SqlCommand("query", conn);
conn.Open();
foreach (var query in sqlqry){
cmd.CommandText = query;
cmd.ExecuteNonQuery();}
conn.Close();
// Need to show alert message as "Patch executed successful. Please send Result Log to Support
// Need to create the result log file.'
You're going to want to use a try catch block
foreach (var query in sqlqry)
{
try
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
string logPath = ""; //Path for log
using (StreamWriter writer = new StreamWriter(logPath, true))
{
writer.WriteLine("Ran query " + query); //W
}
System.Windows.Forms.MessageBox.Show("Patch executed successful. Please send Result Log to Support // Need to create the result log file.");
}
catch (Exception ex)
{
//Handle Error
}
}
You'll need to set a path for where you want to write your log file. After executing the query, the StreamWriter class will write whatever you want to that log file. (The true parameter indicates that you will append to this log file, so each entry doesn't overwrite the last). Then you can use a MessageBox to display the information.
Because the executing of the query is ran inside of a try block, if it fails (some sort of exception happens) it will enter the catch block, in which case you will need to handle that error, perhaps by popping up another message box or logging something to the file.
I'm trying to write a web application with some database interaction in C#.NET. I'm getting an odd exception that I can't figure out where it's coming from. I found the method that it is coming from and the code is as follows:
protected void cmdDelete_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Server=myname-PC\SQLEXPRESS;Database=dbNames;Trusted_Connection=True;"))
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("DELETE FROM Names WHERE FirstName=#FirstName AND LastName=#LastName", conn);
char[] delims = new char[1];
delims[0] = ' ';
string[] names = cblNames.SelectedItem.Text.Split(delims);
string fname = names[0];
string lname = names[1];
comm.Parameters.Add(new SqlParameter("#FirstName", fname));
comm.Parameters.Add(new SqlParameter("#LastName", lname));
comm.ExecuteNonQuery();
conn.Close();
cblNames.ClearSelection();
LoadTable();
}
catch (Exception ex)
{
Response.Write("Delete Table: "+ex.Message);
}
}
}
Any help is appreciated!
You will need to look at the line of code that the error is being thrown at and/or simply debug the application. Otherwise, I can only make guesses as to where this could be occurring:
conn.Open(); //conn could be null (if your connection string is bad it would post back a null connection I believe
cblNames.SelectedItem.Text //cblNames could be null (doubtful), but SelectedItem definitely could
LoadTable(); could be throwing it up also
Without more debug information, that is the best answer you are probably going to get.
so is it saying that cblNames.SelectedItem is null, or that the Split function just isn't returning anything?
Well, it's either one or the other and only you have access to the code, so set a break point at that line and when you hit the break point check if SelectedItem is null or if the Text is null. To be exact, we can eliminate the second "option" since Split always returns something, even if it's just an empty array, it still doesn't return null.
Update
Per your comments, it seems that SelectedItem is not being set, so you must track down what is supposed to set SelectedItem and verify that it's doing it correctly.
Looking at your code, cblNames can only be throwing exception. Check stacktrace for specific line of code.
On the other note, it's not recommended to catch the base exception as catch (Exception ex). Always case specific exceptions instead e.g. System.Data.SqlClient.SqlException or System.InvalidOperationException. For more details check MSDN.
The problem that I was having was that I wasn't getting the value on postback because I was leaving this little peace of code out of the page_load function:
If Not IsPostBack()
It was an elementary lapse in knowledge. I have been developing in .NET since this question and I realize how horribly simple it is to make mistakes in a new language. Thank you everyone for dealing with the past noob me.
I got some data inputed by the user that should be added to a Database File (.sdf). I've choose Sql Server CE because this application is quite small, and i didn't saw need to work with a service based database.
Well any way.
Here goes the code:
public class SqlActions
{
string conStr = String.Format("Data Source = " + new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\basedados.sdf");
public SqlCeConnection SQLCEConnect()
{
SqlCeConnection Connection = new SqlCeConnection(conStr);
Connection.Open();
return Connection;
}
public Boolean AdicionarAuditorio(string Nome, int Capacidade)
{
string Query = "INSERT INTO auditorios (nome, capacidade) VALUES (#Nome, #Capacidade)";
using (var SQLCmd = new SqlCeCommand(Query, SQLCEConnect()))
{
SQLCmd.Parameters.AddWithValue("#Nome", Nome);
SQLCmd.Parameters.AddWithValue("#Capacidade", Capacidade);
if (SQLCmd.ExecuteNonQuery() == 1)
{
return true;
} else {
return false;
}
}
}
}
I use the AdicionarAuditorio(string Nome, int Capacidade) function to Insert the data. running ExecuteNonQuery() which is supposed to return the number of affected rows after he as run the query.
So it should return 1 if the query as successful, right?
In the end he returns 1, but if I browser the table data, the data that the query should add isn't there.
So whats wrong here?
NOTE. If your thinking that the
problem is the connection: I can't see
why is the problem once i got some
Select statements that use that
connection function SQLCEConnect()
and they all work pretty well.
Thanks in advance.
Are you sure you are looking at the right file? When you build your app in VS, it copies the SDF file as content to the target folder, so the database in your project will not reflect any updates. Your code is picking up the the file location there.
This is btw not a good practice, because once deployed, the program folders are not writable to your app (could this be the problem - did you already deploy?). Instead, the database file should reside in your appdata folder.
Is it possible that you make the call to AdicionarAuditorio in a TransactionScope without calling transactionScope.Complete()?