I have developed a C# Windows application in which I need to create a database on client machine for which I have created a script file and installed SQL Server 2008 R2 on client machine.
But when I execute script from my code it always shows an error:
Failed to connect database.
I have added referenced the SMO assemblies from
C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
And my code is :
string sqlConString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=mydatabase;Data Source=(local)";
FileInfo file = new FileInfo(dbPath);
string script = file.OpenText().ReadToEnd();
SqlConnection con = new SqlConnection(sqlConString);
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
How about something like this:
using (SqlConnection cnn = new SqlConnection(sqlConString))
{
var cmds = File.ReadAllText(#"path\to\file").Split(new string[] { "GO" },
StringSplitOptions.RemoveEmptyEntries);
cnn.Open();
foreach (var cmd in cmds)
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.ExecuteNonQuery();
}
}
}
With this approach you get what you want, the script gets executed, but you don't have to use the slow and bloated SMO interface. Further, you're leveraging the using statement so you don't have to worry about unmanaged resources being left open.
Now, to address the failed to connect to database..., which I clearly missed the first time I read it, if that's happening that means this:
Initial Catalog=mydatabase;Data Source=(local)
is likely not right. And if it is, your server may not be accepting Windows Authentication.
I don't know the setup of your local machine, but it's likely that the server is (local)\SQLEXPRESS.
Related
I have two computers. One is running SQL Server, and I can access the server using SQL authentication from the 2nd PC using SSMS.
I have created a C# Windows Forms application that connects to the database. However, I couldn't access my server from the application.
I disabled the firewall, allowed remote control, and allowed mixed mode authentication. I also forwarded required ports to my IP in my router settings.
I tried both these connecting strings, but they didn't help:
"Persist Security Info = False; User ID = gues; Password=gues;Initial Catalog = CoronaNurse; Server=" + server;
"Data Source=" + server + ";Initial Catalog=CoronaNurse;Integrated Security=false;UID=gues;Password=gues";
(server is a string that have IP of my server)
(gues is a login in my Server)
The weird thing is when I login as gues in SSMS from my 2nd computer I can access the server in the first computer.
The question is, how do I access my server from a computer that doesn't have SSMS or any specific Login?
I need my application to be able to connect to my server without anything else installed, but I can't find where my problem is.
Adding from comments:
Im using the connecting to get a con string from my DB depends on the table i get with my gue.login function SqlDataAdapter
adapter = new SqlDataAdapter("select * from gue.login('" + textBox1.Text.Trim() + "', '" + textBox2.Text.Trim() + "', '" + server + "')", conn);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
DataSet ds = new DataSet();
adapter.Fill(ds);
string connection;
connection = ds.Tables[0].Rows[0][0].ToString();
Unless you haven't posted up all of your code, you don't appear to be controlling your SQL connection and I would strongly suggest that you use a parameterised call to protect against SQL injection from using direct text entry field values e.g.:
var dataset = new DataSet();
using (var connection = new SqlConnection(SqlConnectionString))
{
connection.Open();
var command = new SqlCommand("GetAll", connection);
command.CommandType = CommandType.StoredProcedure;
var adapter = new SqlDataAdapter(command);
adapter.Fill(dataset);
...
}
The SQL is wrong, and the connection strings look a little off. You might also need an instance name as part of the server. For example, instead of just localhost or 192.168.0.20, you might need localhost\SQLExpress or 192.168.0.20\..
One way you can find the connection string for sure is to use Visual Studio instead of SSMS to connect to the database. The Visual Studio Database Tools has a similar connection window as SSMS, and you can use it to show you the actual connection string it used.
When you've figured that out, try something more like this:
var connString = $"Server={server};Database=CoronaNurse;User Id=gues;Password=gues";
var sql = "select * from gue.login WHERE username = #username AND pHash = #pHash";
var ds = new DataSet();
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(sql, conn))
using (var adapter = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 50).Value = textBox1.Text.Trim();
cmd.Parameters.Add("#pHash", SqlDbType.Char, 60).Value = BCrypt.Net.BCrypt.HashPassword(textBox2.Text.Trim());
adapter.Fill(ds);
var connection = ds.Tables[0].Rows[0].Items[0].ToString();
}
Note the use of both parameterized queries and BCrypt (you can add BCrypt via NuGet). There are a few things in database development that are too important to do wrong, even for proof-of-concept and learning projects. One of these is SQL Injection. Another is password handling. What I posted still isn't quite right for password handling (you should instead retrieve the stored hash and use the Verify() method), but it's close enough to set you on the right path.
Someone has told me that I can't access my online SQL Server DB from a client PC that doesn't have a Local DB.
I guess that explains my problem perfectly!
I never knew that, in my case, that is my problem right?
I have a legacy Visual FoxPro database from which I need to get the data from.
I have DBC, DCT, DCX & FPT files in the database folder.
I installed the Visual FoxPro provider & driver and wrote a short C# program to access the data.
I also made sure the program is running in 32bit mode, since I understood that the VFP driver is 32bit.
However I'm getting the following error:
Additional information: Connectivity error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I made sure that the driver name ("Microsoft Visual FoxPro Driver") as appears in the Windows ODBC 32bit administration tool is specified in the connection string, but it doesn't seem to help.
The code:
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;DRIVER=Microsoft Visual FoxPro Driver;Data Source=mydatabase.dbc;Mode=Read;Collating Sequence=machine");
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from tablename";
var command = yourConnectionHandler.CreateCommand();
command.CommandText = mySQL;
var res = command.ExecuteReader(); // throws the error
yourConnectionHandler.Close();
}
I've been stuck on this for a long time, and have tried everything I could find on the net.
Any idea?
You are saying provider and trying to use OleDbConnection (which is right) but defining an ODBC driver within the connection string. In other words, your connection string is wrong.
using (OleDbConnection cn = new OleDbConnection(
#"Provider=VFPOLEDB;Data Source=c:\MyPath\mydatabase.dbc;Mode=Read;Collating Sequence=machine"))
using (OleDbCommand cmd = new OleDbCommand("select * from tablename", cn))
{
cn.Open();
var reader = cmd.ExecuteReader();
// do something with the reader. ie:
// someDataTable.Load(reader);
cn.Close();
}
It works wonderfully well. In connectionstring you don't need to use the database name, you can just use the tables' path as the data source.
I have two SQL Server databases, server name are sql1 and sql2.
When I switch database from sql1 to sql2 (using HaProxy), my application still keeps the old SQL connection to server sql1.
However, other applications (using Linq-to-SQL) can get the new SQL connection to sql2.
Please see my code below that's I using to get connection to SQL Server:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
conn.Open();
//do something...
conn.Close();
return data;
}
}
What's my problem? How can I resolve this? Thanks!
You need to know the HAProxy listen configuration, maybe your HAProxy has exceptions programmed, or the redirection only works if you use an specific IP address destination or come from an specific IP range. Please compare the connections string used in each case.
https://www.stevefenton.co.uk/2016/11/load-balancing-microsoft-sql-server-with-haproxy/
I downloaded SQL Server 2012 Express. Using http://www.mssqltips.com/sqlservertip/2694/getting-started-with-sql-server-2012-express-localdb/. I created a local database. Now when I tried to connect to that database using Visual Studio 2010 it throws me error 26
Here is my code:
using(SqlConnection connectionString = new SqlConnection(#"Server=(localdb)\SQLEXPRESS;database=master;Trusted_Connection=True;")
{
connectionString.Open(); //error 26
sql = "insert into Main ([Cable Length1], [Cable Length2]) values(#3',#5')";
using (SqlCommand cmd = new SqlCommand(sql, connectionString))
{
cmd.Parameters.AddWithValue("#3'", 1);
cmd.Parameters.AddWithValue("#5'", 2);
cmd.ExecuteNonQuery();
}
}
Also, I am able to login through SQL Server Management Studio 2012. Can anyone tell me what am I missing?
Ignoring all the other problems1, you should make up your mind as to whether you're using SQL Server LocalDB or not. I am highly doubtful you've made a private LocalDB instance called SQLEXPRESS.
You likely want something along the lines of:
new SqlConnection(#"Server=(localdb)\v11.0;Trusted_Connection=True;")
Or
new SqlConnection(#"Server=.\SQLEXPRESS;Trusted_Connection=True;")
1 being the following:
Your SqlConnection is called connectionString.
Parameters with quotes in their names.
Using master and then trying to insert into a table called Main. System databases are for the system. You are not the system.
I'd expect to see something along the lines of:
using (var connection = new SqlConnection(#"Server=(localdb)\v11.0;Database=MyDatabaseName;Integrated Security=true;")
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [Main] ([Cable Length1], [Cable Length2]) VALUES(#3, #5)";
command.Parameters.AddWithValue("#3", 1);
command.Parameters.AddWithValue("#5", 2);
command.ExecuteNonQuery();
}
}
I got the solution: Make sure you are connected to Database and when you launch sql management studio under server name-->select browse for more-->select database engine and then select your local database. You should see the Green Icon and then you do get connected. Thanks for the help guys!
I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.