SqlConnection, I'm using SQL Server, not LocalDB; so how to - c#

So, in the tutorial I was checking, he uses a Database and connect it using this
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\RANBAH~1\Documents\testlogin.mdf;Integrated Security=True;Connect Timeout=30");
Although, I use SQL Server Management 17, which mean I have a server, So how do i get my SQL Connect Data Source? because afterward he uses it for
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from login where username ='" + textBox1.Text + "' and password='" + textBox2.Text + "'", conn);
Any clue ?

Inside your project, in VS, connect to the server. Once you are on the server explorer, right click on the database to get the connection string. When you check the properties for the database, you should be able to see it.
You cannot get the connection string from SSMS, though you can get all the information for the connection string. Then, you can use those information to create your own connection string using this website: https://www.connectionstrings.com/ Just check which is better suited for you.

Related

Can't access my SQL Server without SQL Engine

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?

Cannot remotely connect to database

Im receiving a MySqlException was unhandled on a line: conn.Open();
MySqlConnection conn = new MySqlConnection("host=fdb5.freehostingeu.com;user=1477630_one;password=******;database=1477630_one;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM users WHERE name = '"+name+"'AND surname = '"+ surname +"';");
cmd.Connection = conn;
conn.Open();
I think the format of my connection string is wrong. and I've tried altering the values to see whether it's the problem but I'm still unable to connect.
what am I doing wrong?
According to their live support, they do not offer Remote Connection to MySQL on the free packages.
ConnectionStrings.com shows this as the correct standard format:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Adjusting yours accordingly:
Server=fdb5.freehostingeu.com;Uid=1477630_one;Pwd=******;database=1477630_one;
See this other answer if you need to allow remote connections to MySQL.
Shared web hosts almost never allow remote access to shared resources such as MySQL. What you will need to do is install a copy of MySQL in your local environment to do you development and testing. Then push your schema out through whatever tools they provide to you - these are usually web based. Then when you push your site to the shared host you the connection string you are using should work fine.
1) Be sure to add a reference to MySQL.Data
2) Include using MySql.Data.MySqlClient
3) Your connection string should be formatted as such:
connectionString = "SERVER=" + yourserver + ";" + "DATABASE=" + databasename + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
4) Do a try-catch statement to catch the errors

ConnectionString Database c#

I am create a database utility and I seem to not be able to get my connectionstring correct.
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
I believe this is in the correct format. As for the data source, my sql server is SQLExpress which runs sql server 2008 R2. My database is named ConfigurationData. Am I missing something?
When I run it, it opens the database - I assume it does since it does not through exception - but when I try inserting into a table, it does not actually insert it yet it executes the command.
conn.Open();
try
{
SqlCommand comm = new SqlCommand("INSERT INTO Test " + "(id,number) " + " VALUES(" + 10 + " , " + 12 + ")", conn);
comm.ExecuteNonQuery();
Console.WriteLine("Database is created successfully", "MyProgram");
}
catch (Exception ex)
{
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
EDIT
Just remembered that I had answered a similar question a while back. Check it out:
Why can't I insert data into local database (SQL Compact Edition) with C#?
I don't think it is the connection string issue. But for your reference, a good site to refer to is http://www.connectionstrings.com/sql-server-2008/
You would need one of these:
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Using an User Instance on a local SQL Server Express instance
The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL
Server instance to a user with limited administrative rights on the computer.
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure 'user instances enabled', '1'. To disable the functionality execute sp_configure 'user instances enabled', '0'.
try (local) instead of dot, dot is not recognized in Win XP
conn.ConnectionString =
"Data Source=(local)\\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|ConfigurationData.mdf;";
You're SQL Statement isn't right also, and you should use parameters, but here is what you should have
SqlCommand comm = new SqlCommand("INSERT INTO Test (id, number) VALUES('" + 10 + " ', '" + 12 + "')", conn);
Why not just use the SqlConnectionStringBuilder class?:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #"(local)\SQLExpress";
builder.UserInstance = true;
builder.IntegratedSecurity = true;
builder.AttachDBFilename = "|DataDirectory|ConfigurationData.mdf";
SqlConnection conn = new SqlConnection(builder.ConnectionString());
The output:
"Data Source=(local)\\SQLExpress;AttachDbFilename=|DataDirectory|ConfigurationData.mdf;Integrated Security=True;User Instance=True"
One of the way to do this is to add your connection string in web.config file as shown below:
Jus click on the properties of database on the database explorer. There you will find connectionstring in its properties. Jus add it in connectionstring below.
<configuration>
<connectionStrings>
<add name="ConnectionName" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Then in the page you can store it in string or directly refer to your connection as shown below:
Connection con=new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["connString"].ToString();
and I suspect your insert statement is not properly declared.
Just try this:
SqlCommand comm = new SqlCommand("INSERT INTO Test (id,number) VALUES('10' ,'12')", con);
That's all from my part... Hope it helped you..

connecting to an SQL Server database

I've recently started programming asp.net with C# (using VS2008) and I wrote my first web application that connects to a database. First version worked ok but now there are some problems once I modify it. I'm giving the examples below which will depict the situation:
1) Works OK. Program connects to a database and uses a function DeleteAllRecords() to perform an action on it; important to note that I created the database to connect to in SQL Server Management Studio.
Code behind page of the button-click event handler:
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("przemek8");
SqlCommand myCommand = new SqlCommand("DELETE FROM table8", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
}
2) the second time I didn't use the database made in SQL SM Studio but I added a new database element from Visual Studio itself (Website -> Add New Item). I added some fields to that database and I also configured a GridView to show the database which is working. The problem, however, is that when I want to connect the Gridview to the database created before in SQL SM Studio, it doesn't work - when configuring the connection it won;t let choose the database file, saying:
You don't have permission to open this file. Contact the owner or an administrator to obtain permission.
It seems to me that the reason for that may be trivial but I cannot sort it out.
Just to note that all that database files were created SQL SM Studio in its default destination on disc C.
3) Not being able to connect with the GridView to the database created by SQL Server I continued working with the database added by Visual Studio itself. It was working with the GridView so I used the function to interact with it (delete all the records) - the same that was used at point 1) but with database now.
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename='D:\\WebSite1\\App_Data\\mydtb.mdf'; Integrated Security=true; User Instance=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("mydtb");
SqlCommand myCommand = new SqlCommand("DELETE FROM Table1", dbConnection);
myCommand.ExecuteNonQuery();
}
catch (SqlException exception)
{
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
dbConnection.Close();
It does not connect to that one and the error message is:
Error code 911: Database 'mydtb' does not exist. Make sure that the name is entered correctly.
I'm new in this field, but should the data source in this case (connecting to the database created in Visual Studio) be Data Source=.\\SQLEXPRESS; as it is when the database is created in SQL Server Management Studio?
Thanks a lot for any help and suggestions!
asp.net excited beginner:-)
The problem your having with regards to connecting to the database on a server is because of
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
The best way to do this is to go to your Web.config file and find the block and add a connection to your database in there.
eg
<add name="ConnectionString" connectionString="Data Source=YOUR SERVER;Initial Catalog=YOUR DATABASE;User ID=YOUR USER ID;Password=YOUR PASSWORD" />
then you can just call the connection string accross your whole project whenever you need to use it.
Also with regards to VS2012. There are very few companies using that IDE at the moment so your probably better off learning VS 2010 in the most part but i would agree that VS2008 is fairly out of date now
i think this will help
SqlConnection dbConnection = new SqlConnection("Data
Source=.\\SQLEXPRESS;Integrated Security=true; initial
catalog=database name; uid=servername ; password=yourpassword");

Connecting to local SQL Server database using C#

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names.
How could I establish a connection to read the table values using C#?
So far I've tried something like this:
SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";
But I get an error:
database not found/error connecting to database
In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
SqlConnection c = new SqlConnection(#"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.
Hope that helps.
Visual Studio 2019 (and probably a few previous versions).
View -> SQL Server Object Explorer
Top of the tree is 'SQL Server'
Under 'SQL Server', are couple of '(localdb)....'
Expand the (localdb)... -> Databases until you find your db.
Database Name (eg. Database1) -> Right-click -> Properties, and scroll the many properties (eg. "ANSI
NULL Default"). Find the "Connection string" property, copy the value
into your code, and you're running.

Categories