I have the following code.
private void CreateDBFFile()
{
string connection = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (OleDbConnection dbconnection = new OleDbConnection(connection))
using (OleDbCommand command = dbconnection.CreateCommand())
{
dbconnection.Open();
command.CommandText = "CREATE TABLE Test (Id Integer, Changed Double, Name Text)";
command.ExecuteNonQuery();
}
}
My web.config file has connection string
<connectionStrings>
<add name="conn"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=k:\temp1"
providerName="System.Data.OleDb" />
</connectionStrings>
I am trying to create a dbf file on my K drive. I keep getting an error on my dbConnection.Open() statement saying:
The Microsoft Jet database engine cannot open the file 'k:\temp1'. It is already opened exclusively by another user, or you need permission to view its data.
K:\ is not a mapped drive. I gave network service userName to temp1 folder by going under security tab. I also gave modify rights to the Network service. Still keep getting this error. I also tried to put the entire above code in console application, that didn't work either. I keep getting the same error.
Any help will be greatly appreciated.
Related
In the following code for a C#.Net windows/desktop application, I have given wrong password while connecting to database but message box still displays Open.
SQLiteConnection conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
conn.Close();
conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;Password=cdssss;");
conn.Open();
MessageBox.Show(conn.State.ToString());
Why it is still open when password is wrong?
This behavior is by design in the .net sqlite driver:
This is by design. The error message only occurs when you try to read from -OR-
write to the underlying database file. Opening the database does not typically
perform either operation.
It is recommended that you execute a SELECT statement on some well-known table
(e.g. "sqlite_master") immediately after opening the database in order to
determine if it is in a usable state.
Cited from Ticket 3eb097e917a7740f3499aae66e9a3cd021e9f81c:
https://system.data.sqlite.org/index.html/tktview/3eb097e917a7740f3499
Good morning guys,
I feel quite silly to ask this question, but I have looked everywhere and possibly at all questions in this matter and could not find a solution that would work for me.
Long story short.
I am using a local database called TestDB.mdf in windows form application. The application is designed to do (as per current) two simple things.
1. Import data from excel document into the database - which I don't have any issues with.
and...
2. Clear all data stored in that database - this is where I am struggling
For the import data into the database (point 1) I am using two connection strings. One for excelConnectionString
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " +
"C:\\Users\\User.AR\\Desktop\\export.xls; " +
"Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
and second for sqlConnectionString
string sqlConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\arkadiusz.rzepka\source\repos\Database_application\Database_application\TestDB.mdf;Integrated Security=True";
Then I use SqlBulkCopy to import all data and all is working like a charm.
Now the issue I can see is that I cannot open a connection to clear all data from the same database.
I have navigated to properties of my database to find connection string and this has been presented in the below format:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User.AR\source\repos\Database_application\Database_application\TestDB.mdf;Integrated Security=True
I have had to amend the above connection string as I was getting errors such as missing provider, should be like Provider=SQLOLEDB, after adding a provider, I have had to change Integrated Security = SSPI, and now I am getting error such as SQL Server does not exist or access denied
My code just to check if the connection was opened is presented below and I would be grateful if you could advise of what I am doing wrong.
private void DeleteAllRecords()
{
string connectionString = #"Provider=Sqloledb;Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User.AR\source\repos\Database_application\Database_application\TestDB.mdf;Integrated Security=SSPI";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
MessageBox.Show("Connection openned successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
If you run this in the command prompt.
SqlLocalDB.exe i "MSSQLLocalDB"
You will get the instance pipe name. You should be able to use that in your OLEDB connection. This has worked for me when connecting Excel using OLEDB connection to my MSSQLLocalDB.
Name: MSSQLLocalDB
Version: 13.1.4001.0
Shared name:
Owner: Foo\Foo.Bar
Auto-create: Yes
State: Running
Last start time: 18/03/2021 09:00:34
Instance pipe name: np:\\.\pipe\LOCALDB#DA1FAFF6\tsql\query
So my final connection string in excel looked like this.
provider=SQLOLEDB;initial catalog=IpsosDC;data source=np:\\.\pipe\LOCALDB#DA1FAFF6\tsql\query
Try using double bar on the paths of your connection strings, instead of one. So it would be like this:
string connectionString = #"Provider=Sqloledb;Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User.AR\\source\\repos\\Database_application\\Database_application\\TestDB.mdf;Integrated Security=SSPI";
I am not sure what I am doing wrong, If I use the connection string shown here, my application works fine.
SqlConnection conn = new SqlConnection();
string DbPath = Application.StartupPath;
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
DbPath = DbPath + "\\MyDatabase.mdf";
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
but if I use connection string here, it's not inserting data into MyDatabase table
conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
My app.config is
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ERPSystem.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=.\EXPRESS2008; AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
INSERT statement and preceding code:
comm = new SqlCommand("CreateUser", MyConnection.MyConn("Open"));
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName.Text;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = userPassword.Text;
comm.Parameters.Add("#UserRole", SqlDbType.VarChar).Value = UserRole.SelectedItem.ToString();
comm.ExecuteNonQuery();
This is the code to get the connection
class MyConnection
{
public static SqlConnection MyConn(string str)
{
SqlConnection conn = new SqlConnection();
try
{
//get application path
string DbPath = Application.StartupPath;
if (Program.RunFrEn == true) //bool var
//remove string after bin folder
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
//add database name with new path
DbPath = DbPath + "\\MyDatabase.mdf";
//generate new connection string for database
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename="
+ DbPath
+ ";Integrated Security=True;User Instance=True";
//conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
if (str == "Open")
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
else
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return conn;
}
}
I am not getting any error
Thank you
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I also had fighted long time with same problem. And I saw many same questions & answers.
You're using |DataDirectory|. I assume you can get values from the DB file and you don't get error to run insert command but the values are not inserted into the DB file.
This is absolutely my private idea and my private conclusion is that this behavior is normal as |DataDirectory| does. I mean a data file of an application should be protected from manipulation once after deployment. The 'Data' file should provide data inside the file so that we can read the data.
Therefore, I coded to create a localDB .MDF file (SQL Server 2014) from users' side so that my applications can utilize the localDB to write and read data. My application automatically downloads data from cloud server which are we need to update frequently. On the other side, I put big and already fixed data into |DataDirectory| .MDF file, I mean inserted big data for read only and add the .MDF file to my project before deployment.
Hope my experience helps.. But, please keep in mind again that this is really my private opinion and I might be totally wrong and my experience is limited only to localDB. But again, I couldn't find a Microsoft's official document mentioning this behavior.
Do you have only 1 option like |DataDirectory|? Did this work to insert before? Is this code by you wrote on your own? If possible, try to find another option rather than |DataDirectory| to connect to the SQL Server database. I use a cloud SQL server with IP address but I can't understand why you use |DataDirectory|. There might be many various options as connection strings to SQL Server Express.
I have the following type of code in my data layer, which can be called from a console app, windows app, etc, with the proper connection string being read from the corresponding caller's App.Config file:
public static udsDataset GetDataset(int datasetID)
{
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string sql = #"select * from Dataset WHERE DatasetID=#datasetID";
using (SqlConnection conn = new SqlConnection(connectionString))
{
// Dapper query:
return conn.Query<udsDataset>(sql, new {datasetID } ).First();
}
}
I now want to call this same code from a SQLCLR stored procedure (within the database where these tables exist), where you would typically use a context connection:
using(SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
// etc etc etc
}
The most obvious approach that comes to mind is to overload the function:
public static udsDataset GetDataset(int datasetID)
{
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
return GetDataset(datasetID, conn);
}
}
public static udsDataset GetDataset(int datasetID, SqlConnection conn)
{
// caller is responsible for closing and disposing connection
string sql = #"select * from Dataset WHERE DatasetID=#datasetID";
return conn.Query<udsDataset>(sql, new {datasetID } ).First();
}
So apps with an App.Config could call the connection-less version and SQLCLR could call the version requiring a SqlConnection.
This "seems ok", but having to write the exact same style of overload for every single similar function makes it feel wrong.
Taking the question (and comments on it) at face-value, why do you need:
the option of passing in an existing connection when calling from a SQLCLR procedure
? You should treat the Context Connection the same as any other connection with regards to Open and Dispose. It sounds like you are thinking that the SqlConnection, when using a Connection String of "Context Connection = true;", needs to be opened only once and then not disposed until completely done, whereas you would Open / Dispose of it several times otherwise. I don't see any reason to have differing behavior in these two scenarios.
All of that aside, how to best handle detecting the change in environment (between Console App and SQLCLR object)? You have two choices, both being probably easier than you are expecting:
Make no changes to the app code, but rely on an additional config file:
You can create a file named sqlservr.exe.Config in the C:\Program Files\Microsoft SQL Server\MSSQL{SqlVersion}.{SqlServerInstanceName}\MSSQL\Binn folder (e.g. C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn, where the 11 in MSSQL11 is for SQL Server 2012). The format of this file, as should probably be expected, is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="CoolioAppDB" connectionString="Context Connection = true;" />
</connectionStrings>
</configuration>
This might be considered "cleaner" code, but does introduce an external dependency that your DBA might be ok with, might dislike but tolerate, or might ask your manager to write you up for ;-).
Make a very minor change to the app code, but don't rely on an additional config file:
You can easily auto-detect whether or not you are currently running in SQL Servers's CLR host by using the IsAvailable property of the SqlContext class. Just update your original code as follows:
string connectionString = "Context Connection = true;"; // default = SQLCLR connection
if (!SqlContext.IsAvailable) // if not running within SQL Server, get from config file
{
connectionString =
ConfigurationManager.ConnectionStrings["CoolioAppDB"].ConnectionString;
}
This usage, by the way, is noted in the "Remarks" section of that linked MSDN page for the IsAvailable property.
Forgive me if this is easy and I have seen similar posts but I am new-ish to C# and have been struggling on this, so any help would be much appreciated.
I am trying to connect to a local DB SQL Server in Visual Studio 2012 but so far have had no luck.
I got my connection string from the properties of my local DB which in the picture is in the left hand pane.
public void connection()
{
string connectionString = "Data Source=(localdb)\v11.0;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
lblConnectionTest.Text = "Connected successfully";
}
catch (SqlException ex)
{
lblConnectionTest.Text = ex.Message;
}
}
At this point, all I am trying to do is establish a connection to the DB and basically write out "connection successful" etc if it connects.
Currently with what I have, I receive the following error:
A network-related or instance-specific error occurred
while establishing a connection to SQL Server.
The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server
is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
What am I doing wrong here?
Many thanks!
Firstly i suggest you to set conenction string in your config file.
link : http://msdn.microsoft.com/fr-fr/library/ms254494(v=vs.110).aspx
Second subject, best practise set your connection in using bloc
link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx
DataSource is your target sql server, access properties of your server and get name, but for your case i think that you want access remotly, so ensure that your firewall server is configured to allow.
If you are in C#, you can create an application config file (App.config), which will be having the connection string with its name.
this is sample code in the app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="myConnString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AppsTest\Nov17RoomBooking\dbRoomBooking.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then Your code should look like this:
private static string sqlConnectionString = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;
private void DeletingDataBase()
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string sqlQuery = "SELECT, INSERT, UPDATE, DELETE";
cmd.Connection = sqlConn;
cmd.CommandText = sqlQuery;
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
catch { }
finally
{
cmd.Connection.Close();
}
}
}
}
I encourage you to start learning LINQ to SQL. In my opinion it's the better way for handling data and interacting with the database. I see you're trying to connect to MySql, but i really don't know if that's possible while using LINQ. I hope someone answers this question.
You can actually solve all of this with few clicks, im using visual studio 2012 and by pulling my ms sql table to the aspx file it actually forms the table on its own and even builds all the connection strings for you.
Your Connection String is wrong.
Correct Syntax for MS SQL SERVER 2012 Express (Built in )
lets suppose my DataBase File is at the path :
C:\Users\Zohair\Documents\Visual Studio 2012\Projects\Learning2\Learning2\Sample.mdf
My Connection String will be :
SqlConnection conn = new SqlConnection("Data Source=(localdb)\\v11.0;Integrated Security=true;AttachDbFileName=C:\\Users\\Zohair\\Documents\\Visual Studio 2012\\Projects\\Learning2\\Learning2\\Sample.mdf");
NOTE: If it gives an error when using single slashes (\) then replace them with double slashes (\\)