Simple SQL Server database connection and reading a table on C# - c#

I am new at this but I have a simple table in my SQL Server with one column name and 2 rows in it. I am trying to show up the names when pressing a button, I need to know how to connect the SQL Server database to the C# code and how to read from a specific table.
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=DESKTOP-REB699D\SQLEXPRESS;Initial Catalog=DBdemo";
cnn = new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
}
}
}
But that didn't work, it crashes at the cnn.open(); line of code.

If you are not using any credentials, its windows authentication.
Does adding Integrated Security=True to the connection string help?
Can you login to the DB without credentials on SSMS using Windows authentication option? If so, you don't need user credentials for connecting to DB. If you require a Username and password there,
you either need to include that in the connection string or
you need to enable SQL Server and Windows Authentication option under security tab to access the database without credentials

Related

Can't Connect C# with SQL Server

I am trying to write a program which interacts with my SQL Server database. I am programming in C# on Parallels on my Mac and SQL Server is running via Docker.
But I just can't connect. I am just getting the same error every time I try.
I have already tried to allow the remote access on SQL Server with:
EXEC sp_configure 'remote access', 1 ;
GO
RECONFIGURE ;
GO
but this does not solve my problem.
Here is my C# code:
main Class
Database database;
public Form1()
{
InitializeComponent();
database = new Database("localhost\\MSSQLSERVER", "user1", "topsecret", "master"); // \
}
private void connect_button_Click(object sender, EventArgs e)
{
database.Connect();
}
Database class:
class Database
{
SqlConnectionStringBuilder builder;
SqlConnection connection;
public Database(string source, string userid, string password, string initialcatalog){
this.builder = new SqlConnectionStringBuilder();
this.builder.DataSource = source;
this.builder.UserID = userid;
this.builder.Password = password;
this.builder.InitialCatalog = initialcatalog;
}
public void Connect()
{
try
{
// Connect to SQL
Console.WriteLine("Connecting to SQL Server ... ");
this.connection = new SqlConnection(this.builder.ConnectionString);
connection.Open();
Console.WriteLine("Connected");
}
catch(SqlException sqle)
{
Console.WriteLine(sqle.Message);
}
}
}
And I am always getting this error:
Network-related or instance-specific error when connecting to SQL Server. The server was not found or can not be accessed. Verify that the instance name is correct and that SQL Server allows remote connections. (provider: SQL Network Interfaces, error: 25 - connection string invalid)
The MSSQLSERVER is the instance name of the unnamed, default instance on your machine - you must not use this in the connection string.
Instead, try this line of code:
database = new Database("localhost", "user1", "topsecret", "master");
Just specify no explicit instance name at all - just localhost (or (local), or .) for the current machine - that's all you need!
It was Problem with Parallels, because Paralles can not access to localhost. So i had to define the IP from Parallels in Visual Studio like this:
database = new Database("10.211.55.2", "user1", "topsecret", "Time");

C# Run SQL Query on another machine

Recently we have had an issue with our ERP retrieving some information from our database tables. While this is being fixed I have come up with some work arounds to temporarily, however, they only work because my user has access to the SQL database and can run queries on the database. I would like to distribute an executable program throughout the company (we are relatively small, so I am not worried about bottle-necking my computer) that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. This way we don't need to make any changes to users SQL permissions.
How could I possibly do this?
Edit - Additional Info
User A - has permission to query the database on our servers from
their workstation
User B - does not have permission to query the db
User B needs to gather information from a specific db query, yet they don't have access to the db. All that User B needs, is to be returned a string with information from that query.
So not necessarily looking for the remote execution of a program per se, because then how would they get that return value?
I would do it with an application that does something like this.
using MySql.Data.MySqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection conn = null;
try
{
conn = new MySqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
MySqlCommand selCmd = new MySqlCommand("SELECT ...", conn);
MySqlDataAdapter da = new MySqlDataAdapter(selCmd);
....
This uses MySql, but the exact equivalent can be done with any DB provider. The part of the connection string that says Integrated Security=False tells the system not to use the current user's window credentials but rather what is being provided in the connection string.
The same thing but using Sql Server, I think, would be like this (it's been a while since I use sql server...
using System.Data.SqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
SqlCommand selCmd = new SqlCommand("SELECT ...", conn);
SqlDataAdapter da = new SqlDataAdapter(selCmd);
....
I assume based on the quote below - you are creating a program that you will send to user B to use to run the query and return a string.
"that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. "
If this is the case - User B doesnt need any data base permissions. You will put your [user A]'s username and password in the connection string of the program you create. So when User B runs this program you gave him, it will use User As permissions to run and return data.
like this:
<add name="myconnection" connectionString="data source=yoursqlserver;initial catalog=yourdataabase;persist security info=True;user id=UserA;password=userAspassword" providerName="System.Data.SqlClient" />

How to connect to database in C# using SqlConnection object?

How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;

Connection String Issues in C# ASP.NET

The current program I am working on is for a Registration page for a shopping cart, I have setup a SQL Server with tables to allow data to be recorded as
UserName,
Email,
Password all are set a Nvarchar(max).
The version of the .NET Framework is 4.5 and I am using VS 2012 and am coding in C#, and the server is an SQL Server instance KENSULLIVAN-PC\KSSQL using integrated Windows Authentication.
So far, I have been able to run the registration page to the point where it will save a cookie of the information but, not send any information to the tables in SQL Server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Account_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
}
//Submit button for user registration information
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
int TheUserID = 5000;
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC/KSSQL;Database=GroupProject; Integrated Security=True");
//INSERT command for values to be updated or added to the Database
SqlCommand comm = new SqlCommand("INSERT INTO RegUser (UserName, Email, Password) VALUES (#UserName, #Email, #Password)", conn);
comm.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#UserName"].Value = RegisterUser.UserName;
comm.Parameters.Add("#Email", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Email"].Value = RegisterUser.Email;
comm.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Password"].Value = RegisterUser.Password;
try
{
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("~/LoggedIn.aspx");
}
catch
{
//ErrorDB.Text = "Error Submitting, Try Again";
}
finally
{
conn.Close();
}
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/LoggedIn.aspx";
}
Response.Redirect(continueUrl);
}
}
What should I be doing differently, what do you notice that is not really recommended?
Thank you,
Kenneth
I see a couple of possible issues.
First, the instance name for SQL databases should be using a backslash. Of course you'll need to escape that backslash, so try this:
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
Second, integrated security can be a little tricky from ASP.NET since often times it's running from a service or system account. You may want to enable MIXED authentication mode in MS-SQL, create a SQL account, and pass in a username and password. I would recommend storing your connection string in the web.config and encrypting it.
Is there a specific error/exception you're receiving? That would be very helpful to us.
First of all #Adam already pointed out, your connection string has issue, for named instance of SQl server, if you are using .Net, it should be backslash
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
OR using #
SqlConnection conn = new SqlConnection(#"Server=KENSULLIVAN-PC\KSSQL;Database=GroupProject; Integrated Security=True");
Second, because you are using Window Authentication, you need to set you ThreadPool which host you web application to run under a windows domain account, which has enough permission to backend database.
If each user using your web site login with windows domain account, and you want to use user's window domain credential to access to backend database, then you need more set up, you need the impersonation, you probably also need constrained delegation.

Login in C# and Microsoft SQL Server 2008

I am very new to the C# programming language. I code primarily in PHP/MySQL and have doen a bit of Java programming.
I have created an admin table in my database that has just 3 fields, AdminID, username and password.
I am using Visual Studio 2010 as my IDE and have already set up my connector to the DB.
I have this so far in my C# code...
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == String.Empty)
{
MessageBox.Show("Fill in your username");
return;
}
else if (textBox2.Text == String.Empty)
{
MessageBox.Show("Fill in your password");
return;
}
//declare variables
String user_name, passwrd;
user_name = textBox1.Text;
passwrd = textBox2.Text;
//SQL select statement
String statement = "SELECT Username, Password FROM Users WHERE Username = 'user_name' AND Password = 'passwrd'";
}
My question is, where do I go from here...i.e. how do I execute the statement, see if a row was returned or not, hash the password input value etc in order to make a successful login script
Please consider using a ready-made solution for implementing security with ASP.NET. Look into using the Sql Membership Provider rather than rolling your own solution. The last thing the world needs is another insecure login implementation.
If you want to use databases in C# , you should start looking at the ADO.NET architecture
The easiest way to perform a read from a database is to use a DataReader, but the problem is there is no native ADO.NET provider for MySQL.
Here is an example with the ODBC provider you could use to read from a MySql DB (for connection string examples you can look HERE
public static void ReadData(string connectionString)
{
string queryString = "SELECT DISTINCT CustomerID FROM Orders";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand(queryString, connection);
connection.Open();
// Execute the DataReader and access the data.
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("CustomerID={0}", reader[0]);
}
// Call Close when done reading.
reader.Close();
}
}
If you want to use a native provider, you can use the MySql Connector/NET developed from the MySql team, it should be structured as any other ADO.NET Data Provider, however i've never used so i can just point you to the documentation from MySQL.

Categories