SQL query does not update table - c#

I have got an UPDATE query, what works well when I execute it in MS Managment Studio.
But if I try execute this query from my c# app, it executes without any exceptions, but does not update the table. Connection string is right.
This is the way I do it:
int contractId = 2
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\tst.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "update аренды set datetime_возврата=GETDATE() where id_договора=#contractId";
cmd.Parameters.Add("#contract_id", SqlDbType.Int, 4).Value = contractId;
cmd.ExecuteNonQuery();
What can be wrong?

If your c# code executes without any exceptions, it updates the database too, but please note you are used AttachDbFilename=|DataDirectory|\tst.mdf in your ConnectionString means the database that is updated is located in the sub-folder BIN\DEBUG folder of your project. If you want to see the updated data just attach the database located in the bin/debug folder in SSMS.
Also as Steve mentioned in comments, for more details read this post.

Related

execute SQL script with USE DATABASE in C#

My query file looks like this:
USE DB_A
GO
SELECT * FROM sch.table;
but my connection string, because of some reason, should be forced to set as #"Data Source=SERVER;Initial Catalog=DB_B; ......"
As ExecuteNonQuery() doesn't support GO, this query will be separated into two parts, i.e, actual code looks like this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnString;
OleDbCommand cmd = new OleDbCommand();
conn.open();
cmd.ComandText = "USE DB_A";
cmd.ExecuteNonQuery();
cmd.ComandText = "SELECT * FROM sch.table";
cmd.ExecuteNonQuery();
conn.close();
it seemsUSE DATABASE doesn't work, it is still reporting errors cannot find object sch.table when executing.
is there any neat solution other than changing my query file or my connection string?
As you've noticed USE doesn't work here. What you can do is fully reference your objects. So instead of
SELECT * FROM sch.table
write
SELECT * FROM DB_A.sch.table
Note that this will only work if you can access DB_A from DB_B with the same credentials you've used to connect to DB_B. If this is not the case you'll have to use a seperate connection to DB_A.
A Solution available is just remove the initial catalog Initial Catalog=DB_B from connection string. Not a perfect solution to this question, but worked in my case.

Dynamic Datasource Path C#

I created an app where a combobox is bound with an Access Database. The application was working fine on my computer because the source path in the connectionstring I defined was related to my computer. I copied the project folder to another computer which gives error of not finding the database at the specified location.
Can I dynamically set the path from a textbox or some other input? Can I call a database from the application where the source path doesn't matter. Even when I refer to Resources.Database1 it still gives full path to application folder for my computer which doesn't work on another computer. Any idea would be appreciated. Thanks!
My code is the following:
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO SubrubDatabaseT(SuburbName,DeliveryTime) values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\WoolsValley\Desktop\Database1.accdb ;
Persist Security Info = False; ";
connect.Open();
command.Connection = connect;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved Successfully");
connect.Close();
}
For your case, the solution is to use an App.config (or Web.config depending on the type of the project you are developing) file and put all the settings there. Then if the path doesn't exist, you can still change it to an existing one in this file, and it will not be necessary to recompile the application.
This is the main use of these lind of files, to add there any settings that could change on the users machines or when the application is published and it may need little adjustments, as in this case, and it may not be needed to recompile for every computer the application runs.
As you mentioned yourself, you can simply have a text box for the file path or maybe an OpenFileDialog component to select the file. You then pass that in the connection string:
//GetFileSource() a method that gets the source from somewhere, like a textbox or a configuration entry in app.config.
var fileSource = GetFileSource();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileSource + ";Persist Security Info = False;";
What's equally important is that you make sure the file actually exists at the destination.
You could create a method that searches the users folder for data files or let the user specify a data file on startup and save that to the users profile directory. There are many ways to do this and which way you choose depends on factors like how is the data file copied to the users PC, are there many data files possible, etc.
If the data file only exists with the app, there is only one data file possible, and the data file is copied/created at deployment time (ie. when you run the MSI) then put it in the app.config instead as a connection element. See Connection Strings and Configuration Files.
First thing is to always use parameterized queries. See https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
Your code refactored with using statements and parameterized inputs.
// get file from the drop down
var filePath = getSelectedDataFile();
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO SubrubDatabaseT(SuburbName,DeliveryTime) values(?,?)";
cmd.Parameters.Add(new OleDbParameter("#suburbName", OleDbType.VarChar)).Value = textBox1.Text;
cmd.Parameters.Add(new OleDbParameter("#deliveryTime", OleDbType.VarChar)).Value = textBox2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
Note that:
OleConnection and OleDbCommand are wrapped in using blocks so they are disposed/cleaned up even when an exception occurs.
Parameters are now used instead of hard coding the string values
Parameters use the correct data types

how to talk to local databases?

I just added a new "local database" in my project using visual studio. Now I added the "New Data Source".
What I want to know is how you can do sql queries to the DB. I know how this is done in PHP but cant find good information about how to do this in C#. All I find is tutorials on how to drag detail or gridviews into the form.
I have one database called 'words' with three tables. I want to be able to do update queries to a row in each of these tables. something like this:
UPDATE easy SET words='blahblahblah' WHERE id=1;
How do you do this?
I am going to use SQL Server as example.
First you need to find out the connection string which should be similar to
_connectionString = "Data Source=(localdb)\\v11.0; Initial Catalog=words;Integrated Security=true;"
and then you do
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE easy SET words='blahblahblah' WHERE id=1;", connection))
{
cmd.ExecuteNonQuery();
}
}

How to detach database and copy db file in local device programmatically in C#

I want to detach the database from SQL Server 2005 from my C# code. I use the DROP query to detach. But it statements delete the file from my local system. I want to detach the database and copy that database in runtime.
First try to connect to the SQL Server without providing any database name,or path just like below:
ConnectionString = #"Data Source= YourDataSource ;Integrated Security=True;Connect Timeout=30";
Note:
YourDataSource can either be . or .\SQLEXPRESS or .\MSSQLSERVER or (local)\SQLEXPRESS or (localdb)\v11.0 or etc.
Then by using the following query, detach your database.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = #"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();
The SQL Server SMO API let's you do anything Sql Server management studio can do (from c# code).
Check out this link
http://msdn.microsoft.com/en-us/library/ms162175.aspx
you can detach a database on SqlServer by the following code:
There is a stored procedure in SqlServedr 'sp_detach_db' for detach a database, has one argument DataBaseName. Here in the code 'MyDatabase' is the database name you should change it with your database name
// C# Code
SqlConnection conn = new SqlConnection("Server=(local); Data Source=;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = "sys.sp_detach_db MyDatabase";
conn.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
You can use stored procedures for your problem. following link can be useful:
http://msdn.microsoft.com/en-us/library/aa259611.aspx
Myo Thu's comments lead me in the right direction, so here's a summary of steps on how to detach the database.
Step 1: Reference the following DLL's in your project [Reference]:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Step 2: using:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
Step 3: Code
var server = new Server(new ServerConnection(#"MyMachine\SQL2012"));
// Ensure database is not in use
server.KillAllProcesses("TestDatabase");
server.DetachDatabase("TestDatabase", true);
EDIT: Now documented in my blog here

Can't create a sql connection due to the fact that it won't rcognize the data source keyword

Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True"); 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;                                                      
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.

Categories

Resources