I have a problem. I cannot fix the problem with The ConnectionString property has not been initialized. The problem is in this method:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand())
{
using (TransactionScope ts = new TransactionScope())
{
products.Update(dataSet, "Produktai");
offers.Update(dataSet, "Pasiulimai");
ts.Complete();
}
}
connection.Close();
}
}
catch
{ }
In the class constructor i already have a SqlDataAdapter and SqlCommandBuilder declared. My connection string is in App.config and it looks like this:
<connectionStrings>
<add name="connectionString" connectionString="server=ANDREW-PC\LTSMSQL;database=MarketDB; Integrated Security=true;" providerName="System.Data.SqlClient" />
In my program I already assigned this connection string parameter to string variable. Here is a code sample:
private string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
Any ideas how I can fix this error?
The command isn't assigned to the connection. You need to use the sqlcommand constructor like so: new SQLCommand(connection, "querystring"). I also suggest you use a newer technology such as ORM. I used basic ADO.NET data access before I found Fluent NHibernate, and Fluent is so much easier to use :-)
why are you using System.Transaction.TransactionScope? are you dealing with multiples transaction aware data sources such as sql server and oracle, where you need a transaction manager to coordinate the transaction? if not, then why don't you create a transaction from the connection?
using (var connection = new System.Data.SqlClient.SqlConnection(" "))
{
connection.Open();
var tran = connection.BeginTransaction();
var cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = connection;
cmd.Transaction = tran;
//I dont know how the sql command relates to this
products.Update(dataSet, "Produktai");
offers.Update(dataSet, "Pasiulimai");
//commit
tran.Commit();
}
Ok, I just found the problem. For some reasons my database was "read only" for me when I connect with visual studio. I have changed some settings in the database and now it works fine. Thanks for your answers. :)
Related
I'm trying to create backup and restore functionality to my Windows form application.
So, I've tried to do a database restore. My code is like this:
string cbdfilename = "c:\\Users\\Public\\Public Document";
SqlConnection.ClearAllPools();
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
string sql;
sql = "Use master;Alter Database BbCon Set Single_User With Rollback Immediate;Restore Database BbCon From Disk = #FILENAME With Replace;Alter Database BbCon Set Multi_User;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#FILENAME", cbdfilename);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Restore DB failed" + ex.ToString());
}
finally
{
con.Close();
con.Dispose();
}
But when I try to run this, I get an error:
Restore db failed System.Data.SqlClient.SqlException(0X80131904):userdoesnot have permission to alter database BbCon.mdf the database doesnot exist or or datbase is not in a state that allows access checks.
Can anyone help me please?
Are you trying to Backup or Restore? You mention Backup in the Title and the commmand is for Restore.
There're not many example cases for localDB yet.
Utilize my code as below. Hope this helps..
For Backup-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection masterdbConn = new SqlConnection())
{
masterdbConn.ConnectionString = master_ConnectionString;
masterdbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = masterdbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE yourdbname SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
masterdbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE yourdbname TO DISK='c:\yourdbname.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
For Restore-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = master_ConnectionString;
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE yourdbname FROM DISK='c:\yourdbname.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
Update-
Oops, sorry, my code is for SQL localDB 2014 but it seems you're using 2012.
Kindly replace (LocalDB)\MSSQLLocalDB to (LocalDB)\v11.0
And kindly just try with above change.
And for your information, as per my experience, if I wrote |Data Directory| in my connectionString, I could only read (SQL SELECT command) the Database. In other word to say, the Insert and Update commands could be done but the database was not inserted or updated actually without any exception. I think setting as |Data Directory| would make the database as read-only and I've found some people were having difficulties to insert or update to database with |Data Directory| setting.
Hope your good days ! Thanks !
So I noticed in my code I had a lot of repetitive connection strings and decided to clean it up a little bit.
My issue is, now that I've put the connection string into a seperate class I can no longer open the connection when using using (InfoTableConnection = new SqlConnection(infoTableConnString))
However if I don't use using it works fine.
I'm not quite understanding how it works I guess. Here is my code if someone could explain what exactly is happening once it's introduced to a class and/or how to fix it.
Connection Class: Connection.cs
class Connection
{
public static SqlConnection InfoTableConnection = null;
public void InfoConnection()
{
string infoTableConnString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True";
using (InfoTableConnection = new SqlConnection(infoTableConnString))
InfoTableConnection.Open();
}
}
Sample Code from:
MainForm.cs
private void zGradeCombo()
{
try
{
//Connection string from class.
Connection connInfoTable = new Connection();
connInfoTable.InfoConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Connection.InfoTableConnection;
cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
cmbType.Items.Add(reader["Type"].ToString());
}
//Close connection from "Connection" class
Connection.InfoTableConnection.Close();
}
//Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The using keyword makes sure that your object will be disposed when you reached the end of the scope so that all the resources will be cleaned up afterwards
using (InfoTableConnection = new SqlConnection(infoTableConnString))
{
InfoTableConnection.Open();
} // <- At this point InfoTableConnection will be disposed (and closed)
Since you care about disposing in the code around you do not need the using block in the constructor of the class. But it would be a good idea to implement IDisposable on your Connection class and use it like this:
using(var con = new Connection())
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con.InfoTableConnection;
cmd.CommandText = "SELECT * FROM [dbo].[Item] ORDER by [Type] ASC";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
cmbType.Items.Add(reader["Type"].ToString());
}
}
In the Dispose() method of your connection you should dispose the SQL Connection.
If your goal is to have your connection string is one location, why not just place your connection string in your app.config (settings) file and reference it in the code from there?
app.config
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MTRInfoTables;Integrated Security=True" />
</connectionStrings>
code.cs
string myConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
You must include a reference to the System.Configuration.dll in your references to use ConfigurationManager.
This way, you can continue using your using statements they way that they were designed to be used.
I am trying to make a simple MS Access Database connection by using the SqlConnection and SqlCommand objects.
As you can see here is how I make the connection:
private SqlConnection GetConnection()
{
String connStr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
return conn;
}
And before you ask, yes I have tried to move this piece of code to the method that calls it. Didn't change anything. It still reads the connection string wrong.
The connection string looks like this and is located in the App.config file:
<add name="ConnString" connectionString="Server=*.*.*.*;Database=familie;User Id=mfs;Password=********;"/>
But when I get this error:
And look at the connection string object at the time, the string looks like this:
"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
I have spent about 2 hours now trying to make this work, going to many different sites to figure out what I did wrong, but I either get information is that is too old, conflicting or deals with connecting to a local database, when this is in fact an external one access through a proxy that was given to me by my client (TrustGate if anyone should ask)
The method that calls GetConnection() looks like this:
public Dictionary<int,String> GetPostNrList()
{
SqlConnection conn = GetConnection();
SqlCommand cmd = new SqlCommand("Execute dbo.HENT_POST_NR_LISTE", conn);
var reader = cmd.ExecuteReader();
Dictionary<int, String> liste = new Dictionary<int, string>();
while (reader.NextResult())
{
int post_nr = (int) reader.GetSqlInt32(0);
String by = reader.GetString(1);
liste.Add(post_nr, by);
}
CloseConnection(conn);
return liste;
}
What exactly am I doing wrong?
The exception message tells you exactly what the problem is - your connection is not open. You just need to open the connection prior to executing a command:
conn.Open();
BTW, a good pattern is to using a using block when dealing with SQL connections, to ensure it gets disposed properly:
using (var conn = GetConnection())
{
using (var comm = xxxxxxx)
{
conn.Open();
using (var rdr = comm.ExecuteReader())
{
// xxxxx
}
}
}
You don't have to specifically close anything - the using pattern does all that for you.
Very new to C# and VS2012.
I'm trying to connect to a local database connection.
Here is the code
string selectSql = "select * from Tasks";
string connectionString = "Data Source=adamssqlserver;database=master;Integrated Security=true;";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(selectSql, cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
//do something
}
}
Here is the error
Keyword not supported: 'database'.
If I put in Initial Catalog first
"Data Source=adamssqlserver;Initial Catalog=etc;"
Then the error gives the same message but for "Initial Catalog".
Here is my data connection
You are using SqlCeConnection not a SqlConnection
This class (SqlCeConnection) is for Sql Compact Edition where the syntax rules of the connection string are different. For example:
Data Source=MyData.sdf;Persist Security Info=False;
Instead your connection string is for a Sql Server or Sql Server Express.
So, if your target database is a SqlServer db as your tag indicates then you need to use
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(selectSql, cn))
{
....
}
Instead of Data Source, try Server, e.g:
string connectionString = "Server=adamssqlserver;Database=master";
This website contains good information for setting up connection string. There are so many options I usually have to turn to a reference to get it set up correctly.
Just a reminder: when using MS Access databases, you need to use OleDbConnection and OleDbCommand, not SqlConnection and SqlCommand. 'Provider' in the connection string for SqlConnection is invalid AFAIK.
Are you missing the " from the connection string section.
Should be
<add name="StevenTestEntities"
connectionString="metadata=res://*/Model.TestModel.csdl|res://*/Model.TestModel.ssdl|res://*/Model.TestModel.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=Data Source=D000097;
Initial Catalog=StevenTest;
Integrated Security=True;MultipleActiveResultSets=True&qout;"
providerName="System.Data.EntityClient" />
Try that out.
I am currently trying to establish a connection between an ASP.NET web site project and a Database built by SQL Server 2008 R2.
The way I am required to do so is to use the connectionString from the Web.config page, but I have no idea what value to give it or how to establish a connection using said value. (Using C#)
Any help would be appreciated, as I found next to no information about the subject.
Here is the (default) value that is currently in the Web.config page:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Use Configuration Manager:
using System.Data.SqlClient;
using System.Configuration;
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using(SqlConnection SqlConnection = new SqlConnection(connectionString));
//The rest is here to show you how this connection would be used. But the code above this comment is all you really asked for, which is how to connect.
{
SqlDataAdapter SqlDataAdapter = new SqlDataAdapter();
SqlCommand SqlCommand = new SqlCommand();
SqlConnection.Open();
SqlCommand.CommandText = "select * from table";
SqlCommand.Connection = SqlConnection;
SqlDataReader dr = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
This article about Connect to SQL Server Using SQL Authentication in ASP.NET will probably give you a better idea of what need to be done.
As a pre check, just check if your mssqlserver services are running.
string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = commandText;
// command.Parameters.AddWithValue("#param", value);
connection.Open();
command.ExecuteNonQuery(); // or command.ExecuteScalar() or command.ExecuteRader()
}