I'm currently learning ADO.NET on C#. I'm learning by a book and tutorials that I found online. I wanted to try some of the samples to get myself familiarized with the whole SQL connnection and command objects and so on. Hence, I tried this:
namespace ConsoleApplication
{
class SqlDemo
{
public void InitConnection ()
{
string connString = #"data source=C:\SQL Server 2000 Sample Databases; database=northwnd; integrated security=SSPI";
SqlConnection conn = null;
try
{
conn = new SqlConnection (connString);
conn.Open ();
Console.WriteLine ("DataBase connection established");
}
catch
{
Console.WriteLine ("DataBase connection not established");
}
finally
{
if (conn != null) conn.Close ();
}
Console.ReadKey (true);
}
static void Main (string[] args)
{
SqlDemo d = new SqlDemo ();
d.InitConnection ();
}
}
}
And no matter how I try, I can connect to the local database. "data source=(local)" don't work.
A couple of things:
1) It looks like you may have a typo in your database name. It should probably be:
database=northwind
2) Your data source should be (local) or . OR you may have an instance installed, in which case you may need to include the instance name as well, such as .\SQLExpress or .\SQLServer.
If you wish to connect to a database file using a path:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
From: http://www.connectionstrings.com/sql-server-2008
However, you may also need to "Attach" the database to Sql Server. In Management studio, right click the Databases folder and select "Attach..."
If you are using SQL Server 2000, then just put 'local' or simply '.' (exclude the quotes) for the data source. And you have a typo in the database name. It should be 'Northwind'
Related
I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1)
I have enabled my IP address within Azure's Firewall rules.
I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.
However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());
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: TCP Provider, error: 0 - The requested address is not valid in its context.)
The C# code;
using System;
using System.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
I've tried temporarily turning off the firewall on my PC, but that made no difference.
The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at.
I created one Azure SQL database and allowed my client IP like below :-
I created one .Net Console application and ran your code, I replaced
using System.Data.SqlClient
with
using Microsoft.Data.SqlClient
You can use any of the above packages.
Copied connection string from Azure Portal > Azure SQL server > Connection string refer below :-
C# Code:-
using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * FROM Products";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
Output :-
I tried to run the code with the connection string format you mentioned in the comments :-
Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And I was able to run the same code above and got the desired output:-
When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below :-
Verify if your connection string has any syntax missing and validate it from Azure Portal.
I ended up taking a copy of the project home and running it on my home PC, and it worked correctly and reliably (after telling Azure to allow that IP address as well)
It turned out the answer was embarrassingly obvious - in addition to the standard Windows 10 firewall, my work PC is running another virus protection/firewall software, and that also needed to be told to allow the app thru.
Definitely one to remember for next time... Although I am kind of intrigued that on two occasions (once mentioned above, once afterwards) out of a few hundred attempts the app did manage to get thru and connect.
Thank you everyone for your answers and help.
I have a sqlite database file in .s3db, It has all the tables and data already populated in it. I am trying to connect to to the database use sqliteConnection. But it does not seem to work..I have added the reference of sqlite.dll, does c# needs some other reference to make the connection? If I make a new sqlite db, it is made as xyz.sqlite, maybe it is not recognizing the database extension.
This is how I am making the connection:
// Creates a connection with our database file.
public void connectToDatabase()
{
//this.dbConnection = new SQLiteConnection(#"data source=Fut_Autobuyer_2012.s3db;version=3;");
string dbConnectionString = #"Data Source=Fut_Autobuyer_2012.s3db";
this.dbConnection = new SQLiteConnection(dbConnectionString);
}
This is what I get when the connection is made:
Database connection not valid for getting number of changes.
Database connection not valid for getting last insert rowid.
Database connection not valid for getting maximum memory used.
Database connection not valid for getting memory used.
It looks like you must open database connection:
using (var connection = SQLiteFactory.Instance.CreateConnection())
{
Debug.Assert(connection != null, "connection != null");
connection.ConnectionString = connectionString;
connection.Open();
try
{
using (var command = connection.CreateCommand())
{
// Execute connection
}
}
finally
{
connection.Close();
}
}
I have a database in Analysis Services on a remote server. This contains a data source for another database located on another remote server.
I am trying to write a connectivity test using C# which will check the database connection between the two databases.
I have been unable to do this using ADOMD.NET. I'm currently looking at using SMO to do this but I haven't had any luck so far.
I would greatly appreciate any advice or suggestions.
Update:
After further research, I have come up with the below test (Please note that I intend to add more try..catch blocks and Assertions later).
Also, this uses C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.AnalysisServices.DLL to access the Server, Database and
DataSource classes.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
try
{
connection.Open();
}
catch (OleDbException e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
I believe that this test is sufficient for my testing (Once I've added some more try..catch blocks and Assertions). If the test passes, it means there are no connectivity issues between my machine and both servers, which implies that there shouldn't be any connectivity issues between the servers.
However, I have been unable to work out how to test the connection between the two servers directly and I am interested if anyone knows a way of doing this.
The best solution I have come across to doing this connectivity test is below:
Please note that this requires the Microsoft.AnalysisServices.DLL to be added as a reference.
class ConnectivityTests
{
// Variables
String serverName = "";
String databaseName = "";
String dataSourceName = "";
[Test]
public void TestDataSourceConnection()
{
try
{
// Creates an instance of the Server
Server server = new Server();
server.Connect(serverName);
// Gets the Database from the Server
Database database = server.Databases[databaseName];
// Get the DataSource from the Database
DataSource dataSource = database.DataSources.FindByName(dataSourceName);
// Attempt to open a connection to the dataSource. Fail test if unsuccessful
OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);
connection.Open();
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
finally
{
connection.Close();
}
}
}
How can I with "code" create a new .mdf/.sdf database?
I've tried this:
http://support.microsoft.com/kb/307283
All it does is fail on the ConnectionString. Since I have no connection to a file that exists before I create it, how can I only connect to the SQL Express Server just to create a mdf/sdf database?
I want to be able to just connect to the server and create the file, from there it probably will be easier to create the tables and such.
Any suggestions?
public static void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
}
Change Catalog=tempdb to Catalog=master, its good worked
Sample use:
var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
if (!System.IO.File.Exists(filename))
{
CreateSqlDatabase(filename);
}
Regarding .sdf files (SQL Server CE), you can use the SqlCeEngine class to create a new database, as described in this MSDN article.
Create .sdf database
using System.Data.SqlServerCe;
using System.IO;
string folderPath="D:\\Compact_DB"
string connectionString;
string fileName =folderPath+"\\School.sdf";
string password = "12345";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine obj_ceEngine = new SqlCeEngine(connectionString);
obj_ceEngine.CreateDatabase();
Make sure you have a valid connection string.
The database/catalog that you need must be set to a valid database, usually this can be the "master" which is always available and since you will be using master to create a database.
If you need to create a database from scratch programmatically i normal go into the SQL Server Management Studio and create it through the gui in a first step. But instead of clicking on the OK button in the bottom right, i click on the Script button in the top toolbar. This will give me a complete sql script for creating the database i'd like to have. Then i can alter the script and change the parts i'd like dynamically.
I suppose the problem is in the ConnectionString. It should point to the valid instance of the master db (as in the article you refer to). Make sure it is correct, and it should work.
Use a connectionString with InitialCatalog = master. Since only master has default access to create a database.
I've tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. I'm essentially just trying to open a connection the database file so I can dump in the data I've pulled out of my excel spreadsheet. I'm using Visual C# making an offline winform application.
No matter what connection string I try in my app.config, it always fails when it tries to write "dReader" to the database.
The error is usually this depending on what string I try:
"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)"
I've gone through many online examples and resources and none seem to work. I'm hoping someone here can point out why it's failing.
Here is my app.config in its latest form:
<connectionStrings>
<add name="DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"
connectionString="Data Source=E:\Other DDP Projects\DDP_Project_SDF\DDP_Project\DDP_Database.sdf;"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Here is my form code:
private void Profiles_Click(object sender, EventArgs e)
{
profilesDialog.FileName = "[YOUR_UPLOAD_FILE_HERE]";
var result = profilesDialog.ShowDialog();
if (result == DialogResult.OK)
{
HandleFileSelection();
}
}
private void HandleFileSelection()
{
var file = profilesDialog.FileName;
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\DDP_Database.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
//Create connection string to Excel work book
string excelConnectionString = string.Format(
#"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=""{0}"";
Extended Properties=""Excel 8.0;HDR=YES;""", file
);
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT [ID],[STATUS],[FAN_NUM],[PROFILE_NAME],[DESTINATION_HOST],[USER_ID],[USER_PASSWORD],[PROTOCOL],[PORT],[PATH],[CONTACT_NAME],[CONTACT_EMAIL],[CONTACT_PHONE],[CONTACT_ALT_PHONE],[CONTACT_CITY],[CONTACT_STATE],[CONTACT_CONTACT_TIME] FROM [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Profiles";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("STATUS", "STATUS");
sqlBulk.ColumnMappings.Add("FAN_NUM", "FAN_NUM");
sqlBulk.ColumnMappings.Add("PROFILE_NAME", "PROFILE_NAME");
sqlBulk.ColumnMappings.Add("DESTINATION_HOST", "DESTINATION_HOST");
sqlBulk.ColumnMappings.Add("USER_ID", "USER_ID");
sqlBulk.ColumnMappings.Add("USER_PASSWORD", "USER_PASSWORD");
sqlBulk.ColumnMappings.Add("PROTOCOL", "PROTOCOL");
sqlBulk.ColumnMappings.Add("PORT", "PORT");
sqlBulk.ColumnMappings.Add("PATH", "PATH");
sqlBulk.ColumnMappings.Add("CONTACT_NAME", "CONTACT_NAME");
sqlBulk.ColumnMappings.Add("CONTACT_EMAIL", "CONTACT_EMAIL");
sqlBulk.ColumnMappings.Add("CONTACT_PHONE", "CONTACT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_ALT_PHONE", "CONTACT_ALT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_CITY", "CONTACT_CITY");
sqlBulk.ColumnMappings.Add("CONTACT_STATE", "CONTACT_STATE");
sqlBulk.ColumnMappings.Add("CONTACT_CONTACT_TIME", "CONTACT_CONTACT_TIME");
sqlBulk.WriteToServer(dReader);
sqlBulk.Close();
excelConnection.Close();
}
private void profilesDialog_FileOk(object sender, EventArgs e)
{
}
}
}
Try this...
First:
Create first a test method which you may check if you can connect to sqlcedatabase.
private void testconnection()
{
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
using (var conn = new SqlCeConnection(string.Format("Data Source={0};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;", strConnection)))
{
conn.Open();
try
{
//your Stuff
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Second:
Just Load your excel file Data into a Datatable and use foreach then save it on your sql ce database file..
//Something like
//oledbcon
//oledb dataadapter
//datatable
// dapt.Fill(dt);
foreach(DataRow excel in dt.Rows)
{
ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
ceCmd.ExecuteNonQuery();
}
Regards
I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. You create the connection using this but then you don't use it. Instead you pass in the connection string to the SqlBulkCopy object which implicitly creates a SqlConnection from that string. I'm assuming it is on that line where you are getting the error. If you notice the namespace of the SqlBulkCopy is System.Data.SqlClient. The reason you are seeing the error is that its trying to go through SQL Server to make the connection and cannot resolve your connection string to a SQL Server database. Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. Stick to using classes in System.Data.SqlServerCe and things should work as expected. You just will have to do the processing in a more manual fashion.
According to this post, SqlBulkCopy isn't supported with SqlCe.