I am creating a Smart Device project using VS2008 for a WIndows CE 6.0 device with .Net Compact Framework 3.5
Here is my code:
string queryString = "SELECT id, name, insert_date, activity FROM dbo.[my Table]";
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection connection = new SqlConnection("Data Source=dba;Initial Catalog=myDb;Persist Security Info=True;User ID=usern;Password=paswd"))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
//command.Connection.Open();
//command.ExecuteNonQuery();
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Debug.WriteLine(errorMessages.ToString());
}
}
Mind that usernames ant table names are changed but I am getting the following errors on command.Connection.Open();
Index #0
Message: Invalid connection.
LineNumber: 0
Source: .Net SqlClient Data Provider
Procedure: ConnectionOpen (Invalid Instance()).
Why and how to fix it? The device easly pings the server machine if that is useful.
at place of command.Connection.Open();
use connection.open()
and after execute query
close the connection...
Yes, open the connection prior to creating the command object, you will not need to close the connection because it is inside the using{}
Related
While using MySQLConnection in C# trying to do a LOAD LOCAL DATA INFILE, how to resolve the error "The used command is not allowed with this MySQL version"
Full error is:
MySql.Data.MySqlClient.MySqlException HResult=0x80004005 Message=The used command is not allowed with this MySQL version
In the connection string, include AllowLoadLocalInfile=true;
Server also need to be set up to allow local load data infile
string connectionStr = "Server=" + server + "; Database=" + database + ";Uid=" + user + ";Pwd="+ pw + ";Port=" + port + "; CharSet=utf8;ConnectionTimeout=6000;DefaultCommandTimeout=6000;";
connectionStr += "AllowLoadLocalInfile=true;"; // Added on separate line for clarity
try
{
sourceConn = new MySqlConnection(connectionStr);
sourceConn.Open();
}
catch(Exception ex)
{
Console.WriteLine("Error opening db connection: " + ex.Message + " trace: " + ex.StackTrace);
}
Here's a list of connection options: https://mysqlconnector.net/connection-options/
I have tried MANY suggested solutions from here but nothing seems to work for this problem. I just keep getting this error message when it hits the 'mdr = command.ExecuteReader();' line. Any thoughts please?
try
{
MySqlConnection connection = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";");
MySqlCommand command;
MySqlDataReader mdr;
connection.Open();
string ThePID = tbPID.Text;
string TheRound = tbRound.Text;
string CurrentPage = tbCurrentPage.Text;
// SELECT #myvar:= myvalue
string query = "SELECT ImageURL, ProofingText " +
"INTO #ImageURL, #ProofingText " +
"FROM Rounds " +
"WHERE ProjectID = " + ThePID + " " +
"AND CurrentRound = " + TheRound + " " +
"AND Page = " + CurrentPage + ";";
command = new MySqlCommand(query, connection);
mdr = command.ExecuteReader();
mdr.Read();
rtProofing.Text = mdr.GetString("#PRoofingText");
tbURL.Text = mdr.GetString("#ImageURL");
tbImagePage.Text = Path.GetFileName(tbURL.Text);
PageBox.Image = Image.FromFile(tbURL.Text);
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you use MySqlConnector, you will get a helpful exception message that explains the problem:
Parameter '#ImageURL' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.
By default, MySQL queries (executed from .NET) can't use user-defined variables. You can relax this limitation by adding Allow User Variables=true to your connection string.
However, this won't fix your underlying problem, which is that this isn't the right way to select data from MySQL.
Firstly, your query is susceptible to SQL injection; you should rewrite it to use parameters as follows:
using (var command = connection.CreateCommand())
{
command.CommandText = #"SELECT ImageURL, ProofingText
FROM Rounds
WHERE ProjectID = #ThePID
AND CurrentRound = #TheRound
AND Page = #CurrentPage;";
commands.Parameters.AddWithValue("#ThePID", ThePID);
commands.Parameters.AddWithValue("#TheRound", TheRound);
commands.Parameters.AddWithValue("#CurrentPage", CurrentPage);
Then, you can retrieve the values with a slight variation on your current code. You must retrieve the values by their column names, which do not have a leading #. You should also check that a row was retrieved by examining the return value of Read():
if (mdr.Read())
{
rtProofing.Text = mdr.GetString("ProofingText");
tbURL.Text = mdr.GetString("ImageURL");
}
Finally, string concatenation is also not the right way to build a connection string. The MySqlConnectionStringBuilder class exists for this purpose; use it.
var builder = new MySqlConnectionStringBuilder
{
Server = server,
Database = database,
UserID = uid,
Password = password,
};
using var connection = new MySqlConnection(csb.ConnectionString);
I'm restoring a SQL Server .bak file on SQL Server Express. But after restoring the database, I cannot use it in my code, it seems that the file is somehow locked, and the only way is copying it to another folder, also when I try to copy the .mdf file (using Windows Explorer) I get a warning about admin permission. I cannot copy this file using C# File.Copy (unauthorizedaccessexception, access denied), here is my code:
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH FILE = 1, MOVE N'IODB_Data'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
//here I'm going to connect to my newly created & restored database, but I get access denied error
SqlConnection sql = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + #"\" + dbname + ".mdf ;Integrated Security=True");
sql.Open();
What is going wrong here? I want to connect to my newly restored database as soon as I restore my database.
I get following error when I try to connect to my newly created & restored .mdf:
Unable to open the physical file "D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf". Operating system error 5: "5(Access is denied.)".
An attempt to attach an auto-named database for file D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I suspect it may be already attached.
Can you connect using:
new SqlConnection("Server=" + sqlname +
";Integrated security=SSPI;" +
"database=" + dbname);
I have an c# winforms application (.net 2 framework).
I need to backup data bases from my application.
I am trying to do this by executing an SqlCommand asynchronously.
The code is executed with no exceptions but I dont get the .bak file in my destination...
this is the code :
#region backup DB using T-SQL command
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS") + ";Initial Catalog=" + db + ";UserID=" + ConfigurationManager.AppSettings.Get("user") + ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK=" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" + db + ".bak'", sqlConnection1))
{
sqlConnection1.Open();
IAsyncResult result = cmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
Thread.Sleep(100);
}
}
}
#endregion
In your SQL backup line you seem to be missing a single quote at the beginning of the path to the backup file.
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1))
Two advices to try to isolate the problem:
1) Get the resulting string (the one you are executing on the SqlCommand and run it manually on SQL Server to make sure the backup commnad is correct.
2) Try a synchronous command with a regular ExecuteNonQuery to see if you are getting a SQL Server exception
You should call EndExecuteNonQuery() on your SqlCommand instance in order to throw any eventual exception and thus understand what is wrong with your SQL statements:
IAsyncResult result = cmd.BeginExecuteNonQuery();
// Wait for the command to complete
result.AsyncWaitHandle.WaitOne();
// End the execution and throw any eventual exception
cmd.EndExecuteNonQuery(result);
As you can see, I have also replaced your original Thread.Sleep() cycle block with a more effective wait on the wait handle of the command.
Quoting MSDN:
For each call to BeginOperationName, the application should also call
EndOperationName to get the results of the operation.
I keep getting this error:
Invalid object name "CAccounts".
and the code I have is:
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
// Set ConnectionString.
String sConSg =
"CONNSTRING HERE";
using (SqlConnection connection = new SqlConnection(sConSg))
{
try
{
connection.Open();
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
try
{
SqlDataReader slrr = null;
SqlCommand command = new SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode = " +
"'" + _activationcode.Text + "'", connection);
slrr = command.ExecuteReader();
while (slrr.Read())
{
if (slrr["ActivationCode"].ToString() == _activationcode.Text)
{
MessageBox.Show(slrr["ActivationCode"].ToString(), "AutoOptimise");
}
else
{
}
}
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
}
});
thread.Start();
Can somebody please shed some light?
The table CAccounts you're referencing in your select clause probably doesn't exist in the database. Check that.
See a list of possibilities here:
http://web.archive.org/web/20150519073601/http://sqlserver2000.databases.aspfaq.com:80/why-do-i-get-object-could-not-be-found-or-invalid-object-name.html
I'd suggest these things:
check which schema the object CAccounts is under. Is it dbo or other? Does the user have permissions on that schema?
login to SQL Server via Management Studio. Use the credentials in the connection string that the code is using. Paste & run the SQL statement above.
use SQL Profiler to capture/verify ensure the SQL statement as it crosses to your SQL Server. Run THAT as an adhoc query against that SQL Server.
are there any funny DNS issues? Hosts files? Does this happen during debugging or on the app server?
is the database server name correct? i.e. localhost versus a named server. Try addressing by the IP address that you expect it to be run at, just for fun, both in your connection string, and via SSMS.
Instead of CAccounts, I had to label it DATABASENAME.dbo.CAccounts.
So it would be something like:
"SELECT * FROM DATABASENAME.db.CAccounts"
This might work:
SqlConnection con = new SqlConnection("Data Source=192.168.1.12;Initial Catalog=Ibrahim;User ID=sa;Password=1412;");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Ibrahim.EVC_Activation_Val (Date,Dealer,Transaction_ID,Invoice_ID,Mobile_Num,Quantity_LE) values('" + DateTimePicker1.Value.ToString("yyyy/mm/dd") + "','" + Txtbx1.Text + "','" + Txtbx2.Text + "','" + Txtbx3.Text + "','" + Txtbx4.Text + "','" + Txtbx5.Text + "')",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
con.Close();