How to kill a SQL Server session or session ID - c#

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

Related

Sql insert c# windows forms

I am working on a windows form project with a sql database I want to write some data but I couldn't. (the code doesn't give any error however no data is written.
The code below is the place where I want to write the data:
public static string stringConnection = #"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\POS.mdf; Integrated Security=True";
try
{
mySql = string.Empty;
mySql += "INSERT INTO Journal (Date) VALUES (" + "'"+ caisse + "'"+")" ;
connection.exsql(mySql);
}
catch(Exception exx)
{
MessageBox.Show(exx.ToString());
}
and here is the connection.exsql method:
public static void exsql(string sql)
{
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = default(SqlDataAdapter);
try
{
connection.ConnectionString = stringConnection;
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
connection.Close();
//connection = null;
}
catch (Exception ex)
{
MessageBox.Show("Fatal sql error: " + ex.Message, "Sql Server connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You want to use the sqlCommand and execute .ExecuteNonQuery() to do an INSERT or UPDATE.
More info here.
Also, use parameterization (an example is shown in the link above), otherwise, you open yourself up to SQL injection and your code will fail if your variable contains a single quote.
Less code
private bool exsql(string query)
{
using(var conn = new SqlConnection(ConnectionString.path))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
return command.ExecuteNonQuery() == 0 ? false : true;
}
}
SqlConnection con;
SqlCommand cmd;
public bool exsql(string query)
{
try {
con = null;
con = new SqlConnection(ConnectionString.path);
cmd = new SqlCommand(query, con);
con.Open();
var rowEffected = cmd.ExecuteNonQuery();
con.Close();
if(rowEffected>0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception occurred !",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You can execute your query by ExecuteNonQuery() function

how to backup and restore mdf file in winform C# after deployment project?

I am developing a desktop application in c# visual studio 2013, where I want to create a feature in which a user is allowed to restore and backup the Database by itself. but problem is that it doesn't backup or restore database after deploy project.
When I try to Backup it says!
Database 'DatabaseName' does not exit.Make sure the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
When I try to Restore Database it says
System.Data.Sqlclient.SqlException (0x80131904): User does not have permission to alter database .mdf', the database does not exit, or the the database in not in a state that allows access checks. and so on!
I am using SQL Server Express 2012 by attaching mdf file to the application, when i try to backup using query it works when i add Connection String through SQL Server but after attach mdf file i won't work .
have watch some tutorial videos and figured out some codes but I got nothing
here is my BACKUP code!
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
String sql = "BACKUP DATABASE neyadatabase TO DISK = '" + backuploca.Text + "\\neyadatabase - " + DateTime.Now.Ticks.ToString() + ".Bak'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show("backup done successfully!");
con.Close();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and here is my RESTORE Code!
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\neyadatabase.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
string sqlStmt2 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE DATABASE [neyadatabase.mdf] FROM DISK='" + restoreloca.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER DATABASE [neyadatabase.mdf] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successefully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I am a beginner in this if anyone is going to help me please give some example too so that I can better understand!
Thank you
For backup use :
private void buttonbackup_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConn = new SqlConnection())
{
dbConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
dbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = dbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE neyadatabase SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
dbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE neyadatabase TO DISK='c:\neyadatabase.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And for restore :
private void buttonrestore_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=neyadatabase;Integrated Security=True;Connect Timeout=30;";
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE neyadatabase FROM DISK='c:\neyadatabase.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Backup and restore bak file. Mdf/ldf is for attaching not backup.
I hope this helps you.
If you faced any problem let me know to update my answer ;). Good luck

Connection to SQL Server Express from 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();
}
}

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;
...
}
}

Fill: SelectCommand.Connection property has not been initialized

After a while using the website, loading contents, etc.. this message shows "Fill: SelectCommand.Connection property has not been initialized"!
I think this is because the sql connection, but not sure... I'd like to know what can i do to prevent this, every time this happens i have to upload a file (SQL class, that make the connection) and the website starts to work again.
My SQL connection:
public class SQL
{
SqlCommand comandos;
public SqlConnection sql()
{
string Server = #"server";
string Username = "user";
string Password = "pass";
string Database = "database";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
SqlConnection Connection = new SqlConnection();
try
{
Connection.ConnectionString = ConnectionString;
Connection.Open();
return Connection;
}
catch (Exception)
{
if (Connection != null)
{
Connection.Dispose();
}
return null;
}
}
public void FazerComando(string comando)
{
comandos = new SqlCommand(comando, sql());
comandos.ExecuteNonQuery();
}
public DataTable Execute(string comando)
{
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, sql());
DataTable dtResult = new DataTable();
SQLDataAdapter.Fill(dtResult);
return dtResult;
}
}
This might be related to your problem, but in any case, it's something that should be addressed: You're not disposing your connections when you're done with them. You should use using:
public void FazerComando(string comando)
{
using (var conn = sql())
{
comandos = new SqlCommand(comando, conn);
comandos.ExecuteNonQuery();
}
}
public DataTable Execute(string comando)
{
using (var conn = sql())
{
SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(comando, conn);
DataTable dtResult = new DataTable();
SQLDataAdapter.Fill(dtResult);
return dtResult;
}
}
I've never taken that approach before. We usually just use the connection string in web config, expecially with linq, it works very well. I suggest you have a look at http://blogs.msdn.com/b/visualstudio/archive/2012/06/11/world-of-samples-at-your-fingertips.aspx and follow the trail. You should find a good example of a recommended best practice for connections. The connection string will then be read at the first lauch of your app, and connection pooling (v imortant) used to best effect.
Oh and you are not disposing of your connection, which will cause a memory leek and iis to clear out your app pool when the memeory usage becomes too large -- all v bad
As the other respondant says whilst I was looking up the baet prac link...
HTH

Categories

Resources