Connection to SQL Server Express from C# - c#

I tried to open a connection with SQL Server Express and assign a new record on a specific table in C#.
This code is giving me this error
ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
And the following:
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)
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection("Server=HABCHY-PC/SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=mydatabase;" +
"User Instance=true;"+
"Connection timeout=30");
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) "+
"Values ('string', 1)", myConnection);
myCommand.ExecuteNonQuery();
try
{
SqlDataReader myReader = null;
myCommand.CommandText = "select * from students";
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Please tell me what's the problem.

I think this should work for you:
using System;
using System.Linq;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
public static SqlConnection GetConnectionsString()
{
return new SqlConnection("Server=HABCHY-PC\\SQLEXPRESS;" +
"Trusted_Connection=true;" +
"Database=mydatabase;" +
"User Instance=true;" +
"Connection timeout=30");
}
static void Main(string[] args)
{
using (SqlConnection myConnection = GetConnectionsString())
{
try
{
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) " + "Values ('string', 1)", myConnection);
Console.WriteLine("ee");
myConnection.Open();
myCommand.ExecuteNonQuery();
SqlDataReader myReader = null;
myCommand.CommandText = "select * from students";
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
As you can see I extracted the SQLConnection in another method.
This will help you when you want to make other database requests later.
With the using block you can make shure that your connection will be closed even if you got an exeption in your request.

Your mixing two approaches:
(1) either you have the database on the server and you access it via its logical database name (my preferred solution) - but in that case, you must not have a User Instance in your connection string - use this:
Server=HABCHY-PC\SQLEXPRESS;Database=mydatabase;Connection timeout=30;Integrated Security=SSPI;
( also note: the SQLEXPRESS instance name should be after a backslash - not a forward slash)
(2) or then you have the database as a on-disk .mdf file and it's not attached to the server (which is a messy and kludgy affair in my opinion). In that case, you have the User Instance, then then you need to specify the .mdf file as a file:
Server=HABCHY-PC\SQLEXPRESS;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
Connection timeout=30;Integrated Security=SSPI;

May be your problem is here Trusted_Connection=yes; replace it with Trusted_Connection=True;.
if you are trying to use User Instance in connection string then you could use connection string like this
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
you can get more connection string sample here

This will probably not be the answer to the question but I wrote this answer to help you write better code (not perfect probably :) ). I think you don't completely understand the concept of the use of a try-catch statement. There's not only try and catch but also the keyword finally. Everything in this statement will be executed, even when an exception is thrown. This way, you can handle the closing/disposing of variables if still needed, or execute other code that must be done, even when a exception is thrown.
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection("Server=HABCHY-PC/SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"Database=mydatabase;" +
"User Instance=true;"+
"Connection timeout=30");
SqlCommand myCommand = new SqlCommand("INSERT INTO students (firstname, age) "+
"Values ('string', 1)", myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myCommand.CommandText = "select * from students";
SqlDataReader myReader = myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["firstname"].ToString());
Console.WriteLine(myReader["age"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
myReader.Close();
myConnection.Close();
}
}

Related

C# odbc connection to sql creating tables but dont see in SQL Server

I want to create tables in SQL Server in my program. The code compiles and everything seems to be ok, but after I close it the tables don't appear in the SQL Server database.
EDITED
Please help here is the code and the connection string:
connectionString = "Driver={Sql Server}; Server=baxu\\sqlexpress; Database = baza1;" + $"UID ={ username };PWD={ password };";
Code:
try
{
using (OdbcCommand comm = new OdbcCommand())
{
comm.Connection = cnn;
comm.CommandText = cmdString;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
This here should work for you:
NB: If you dont use trusted connection - Then look at the different connectionstrings here:
var conn = new OdbcConnection();
conn.ConnectionString =
#"Driver={SQL Server};" +
#"Server=EGC25199\SQL2016;" +
#"DataBase=LegOgSpass;" +
#"Trusted_Connection=Yes;";
try
{
string cmdString = "CREATE TABLE dbo.odbctable (Wartosc int, Czas datetime)";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(cmdString, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
This might help. I noticed you used an unassigned name in the create command.
using System;
using System.Data;
using System.Data.Odbc;
class CommandOdbcExample{
static void Main() {
OdbcConnection comm = new OdbcConnection(#"DSN=MyOdbcdDB");
OdbcCommand nonqueryCommand = comm.CreateCommand();
try {
comm.Open();
nonqueryCommand.CommandText = "CREATE TABLE MyTable (Wartosc int, Czas datetime)";
Console.WriteLine(nonqueryCommand.CommandText);
nonqueryCommand.ExecuteNonQuery();
}
catch (OdbcException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
comm.Close();
Console.WriteLine("Connection Closed.");
}
}
}

How to insert data into MySQL database using Asp.net

I am trying to insert data into MYSQL database using Asp.Net but I am getting the following error message: Failed to connect to the database due to System.InvalidOperationsException.The connection must be valid and open.
Here is what I am doing:
protected void SU_Button_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=mno; Database=xyz; User ID=abc; Password=abc";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
string insertData = "insert into signup_table(firstname,surname,mobile_number,email_address,password," +
"confirm_password) values (#F_Name, #S_Name, #M_Number, #E_Address, #Password, #C_Password)";
MySqlCommand command = new MySqlCommand(insertData, connection);
command.Parameters.AddWithValue("#F_Name",FN_TextBox.Text);
command.Parameters.AddWithValue("#S_Name", SN_TextBox.Text);
command.Parameters.AddWithValue("#M_Number", MN_TextBox.Text);
command.Parameters.AddWithValue("#E_Address", EA_TextBox.Text);
command.Parameters.AddWithValue("#Password", P_TextBox.Text);
command.Parameters.AddWithValue("#C_Password", CP_TextBox.Text);
int result = command.ExecuteNonQuery();
connection.Open();
MessageBox.Show("Connected to database");
MessageBox.Show("Data inserted successfully");
}
catch(Exception ex)
{
MessageBox.Show("Failed to connect to database due to" + ex.ToString());
MessageBox.Show("Failed to insert data due to" + ex.ToString());
}
}
}
Please suggest something. Thanks in advance... :)
You have to open your connection before you execute the query.
connection.Open();
int result = command.ExecuteNonQuery();
also dont forget to close your connecion after you finished.
change this
int result = command.ExecuteNonQuery();
connection.Open();
to this
connection.Open();
int result = command.ExecuteNonQuery();

How to kill a SQL Server session or session ID

I'm trying to kill a session in SQL Server 2012 from C# windows Form using kill <spid> but what happens is that when I do that, an error appears:
Cannot use KILL to kill your own process
Code:
// to do DB backup
private void spid2_Click(object sender, EventArgs e)
{
string SQLDataBases;
SQLDataBases = "select ##spid ";
SQLDataBases += "BACKUP DATABASE School TO DISK = \'C:\\Program Files\\Microsoft SQL Server\\MSSQL11.MSSQLSERVER\\MSSQL\\Backup\\AdventureWorks333.BAK\' ";
string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
SqlConnection cnBk = new SqlConnection(svr);
Command = new SqlCommand(SQLDataBases, cnBk);
Command.CommandText = SQLDataBases;
SqlDataAdapter da = new SqlDataAdapter(Command);
DataTable dtDatabases = new DataTable();
try
{
cnBk.Open();
da.Fill(dtDatabases);
label1.Text = dtDatabases.Rows[0][0].ToString();
}
catch (Exception ex)
{
string s = ex.ToString();
MessageBox.Show(s);
label1.Text = dtDatabases.Rows[0][0].ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk.Close();
cnBk.Dispose();
}
}
}
// to kill backup session
private void kill_Click(object sender, EventArgs e)
{
string SQLRestor;
SQLRestor = "Use master; kill " + label1.Text;
string svr = "Server=" + localsrv + ";Initial Catalog=master;Integrated Security = SSPI;";
SqlConnection cnRestore = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLRestor, cnRestore);
try
{
cnRestore.Open();
cmdBkUp.ExecuteNonQuery();
}
catch (Exception ex)
{
string s = ex.ToString();
}
finally
{
if (cnRestore.State == ConnectionState.Open)
{
cnRestore.Close();
cnRestore.Dispose();
}
}
}
Always use "using" for disposable classes (also to close and dispose), never concatenate string in query, use always parameterized query to avoid sql injection. This is sample how to use SqlConnection, SqlDataAdapter, and SqlCommand :
var connectionString = "...";
var sqlQuery = "...";
// Sample using SqlCommand
try
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand(sqlQuery, conn))
{
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("OK, SqlConnection and SqlCommand are closed and disposed properly");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
// Sample using SqlDataAdapter
try
{
var dataTable = new DataTable();
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var sda = new SqlDataAdapter(sqlQuery, conn))
{
sda.Fill(dataTable);
}
}
MessageBox.Show("OK, SqlConnection and SqlDataAdapter are closed and disposed properly, use DataTable here...");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex);
}
The "Cannot use KILL to kill your own process" is there for a reason. If you're finished using your session, close the connection: SqlConnection is an IDisposable, so wrapping it in an using() {} block will close it automatically when you're done using it. This will return the connection handle back to the pool, and it is up to the SQL server client components to decide whether to keep it around for follow-up connections, or dispose it. SQL server does a good job of managing its process lifecycle and killing them is an administrative option, but nothing that an application in normal operation should do (except for a few reasons, see here)
That said, to answer the actual question: to kill process A, you'd have to open a second connection B and KILL A's process (SPID). This will work as long as the assumption "one SPID = one connection = one session" holds (true for all current SQL server versions).
Furthermore, your user needs the ALTER ANY CONNECTION privilege. This is usually limited to sysadmin and processadmin roles, and your application is unlikely to have this in a production environment.
References:
http://www.sqlservercentral.com/Forums/Topic1503836-1292-1.aspx
http://sqlserverplanet.com/dba/spid-what-is-it

SQL c# insert Command doesn't work

I'm having a problem insertin data into my database.
I can read from the database by using the select query, so I know my connection string is correct, but for some reason the insert doesn't work.
Here's my code:
private string ConnectionString()
{
return #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\dbBusiness.mdf;Integrated Security=True;User Instance=True";
}
private void Insert()
{
try{
string sqlStrInsert = "INSERT INTO myTable ([param1],[param2])VALUES(#param1,#param2)";
SqlConnection connection = new SqlConnection(ConnectionString());
SqlCommand command = new SqlCommand(sqlStrInsert, connection);
command.Parameters.Add("#param1", SqlDbType.SmallInt);
command.Parameters.Add("#param2", SqlDbType.NVarChar,50);
command.Parameters["#param1"].Value = numOf_company;
command.Parameters["#param2"].Value = txt_name.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
}
It doesn't show any exeption, and when I check my table through the Visual studio explorer
nothing is added to the table.
Im having trouble figuring this out so
i'd appreciate anyone who helps
I believe you forgot your Initial Catalog in your connection. Because without it your code will try to run in master (the default database).
Here is a snippet that should help you, you will need to modify the code obviously for your benefit.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Working
{
class Program
{
static void Main(string[] args)
{
string DsQuery = "INSERT INTO table (param1,param2)VALUES(#param1,#param2)";
string TgtServer = #".\SQLEXPRESS";
DataSet dsServers = new DataSet();
dsServers = ExecQuery(DsQuery, TgtServer, "InitialCatalog");
}
private static DataSet ExecQuery(string strQuery, string strServer, string strIC)
{
string connectionString = #"Data Source=" + strServer + ";Initial Catalog=" + strIC + ";Integrated Security=SSPI";
string commandString = strQuery;
DataSet ds = new DataSet();
try
{
SqlDataAdapter da = new SqlDataAdapter(commandString, connectionString);
da.Fill(ds, "Table");
}
catch (SqlException e)
{
Console.WriteLine("An SQL Exception Occured: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("An General Exception Occured: " + e.Message);
}
return ds;
}
}
}
Sorry I can't give you anything more but that is something I noticed was missing and based on the no error given I can't provide.
Here is further reading:
http://technet.microsoft.com/en-us/library/aa905872(v=sql.80).aspx
Who is TABLE!?!? The name of your table? If yes, please change this name because if a reserved keyword
INSERT INTO table (param1,param2)VALUES(#param1,#param2)
becomes (for example)
INSERT INTO myTable (param1,param2)VALUES(#param1,#param2)

Unable to access the Microsoft Access database using asp.net and C#

This is code i wrote to add some text to accordion pane on a button click:
protected void Button1_Click1(object sender, EventArgs e)
{
//Use a string variable to hold the ConnectionString.
string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb";
System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection();
cn.ConnectionString = connectString;
//Create an OleDbConnection object, and then pass in the ConnectionString to the constructor.
//OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString);
try
{
//Open the connection.
cn.Open();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl("Open Error"));
}
string selectString = "SELECT * FROM BasicInfo";
//Create an OleDbCommand object.
//Notice that this line passes in the SQL statement and the OleDbConnection object
OleDbCommand cmd = new OleDbCommand(selectString, cn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
//Note: The OleDbDataReader is forward-only.
try
{
OleDbDataReader reader=null;
try
{
reader = cmd.ExecuteReader();
}
catch (Exception es)
{
AccordionPane1.Controls.Add(new LiteralControl(" datareader"));
}
string s = "s";
reader.Read();
s = reader["S_No"].ToString();
AccordionPane1.Controls.Add(new LiteralControl(s));
//Close the reader and the related connection.
reader.Close();
cn.Close();
}
catch (Exception ex)
{
AccordionPane1.Controls.Add(new LiteralControl(" Read Error"));
}
}
I have my access 2007 database in the folder i specified in the connectString. When im viewing in the browser, on the button click i am getting all the three exceptions:
What might be the problem in opening the database? Do i need to make any other changes?
Change
Provider=Microsoft.Jet.OLEDB.4.0;
to
Provider=Microsoft.ACE.OLEDB.12.0
Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=D:\\C#Samples\\StudentDetails\\WebRole1\\App_Data\\Students1.accdb
Hopefully it will solve the issue.
you connection string might be cause of isssue
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\abc.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
this For access 2007 also check the path of database is cocrect.
You can use |DataDirectory| instead of real path and you have to change the Provider=Microsoft.ACE.OLEDB.12.0 (as suggested by #MMK)
string connectString = #"Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\Students1.accdb;Persist Security Info=False;";
and always use using block which dispose IDisposable objects properly.
using(OleDbConnection cn=new OleDbConnection())
{
using(OleDbCommand cmd=new OleDbCommand())
{
cn.ConnectionString=connectionString;
cmd.CommandText=selectString;
cmd.Connection=cn;
...
}
}

Categories

Resources