Having trouble with SQL Delete on SQL Server using C# - sql-server

I am running this code but it throws an exception and I am not sure why. Any help would be appreciated. I checked the ID and it was the right ID for the record.
protected void DeleteSQLDB(int id)
{
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=" + id;
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
m_dbConnection.Open();
cmd.ExecuteNonQuery();
m_dbConnection.Close();
}
}
}
catch (Exception ex)
{
Response.Redirect("somwhere");
}
finally
{
}
}

I solved the problem. The reason was that the record was referenced in other tables so I had to remove the references before I could remove the record. Thanks user7396598 for advice about running query manually. This is the code which removes the conversations first and then the student record:
//This deletes the archived student, First any conversations need to be deleted before the record can be removed.
protected void DeleteSQLDB(object id,String studentID)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblConversations WHERE StudentID=#studentID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#studentID", studentID);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
DeleteSQLDB2(id);
}
}
protected void DeleteSQLDB2(object id)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=#ID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#ID", id);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
Response.Redirect("studentgrid.aspx");
}
}

Related

SqlDependency Works with local DB but not with servers

using this code:
private async Task<object> ChatNotification()
{
try
{
string cs =dbConnectionStr;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string cmdText = #"SELECT
[dbo].[ChatMessage].[Id],
[dbo].[ChatMessage].[fkUserId],
[dbo].[ChatMessage].[fkGroupId],
[dbo].[ChatMessage].[Message],
[dbo].[ChatMessage].[DateTime],
[dbo].[ChatMessage].[IPAddress]
FROM [dbo].[ChatMessage] ";
SqlClientPermission permission =
new SqlClientPermission(
PermissionState.Unrestricted);
try
{
permission.Demand();
}
catch (System.Exception ex)
{
}
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.Notification = null;
SqlDependency tradeInfoDependency = new SqlDependency(cmd);
tradeInfoDependency.OnChange += DependencyNotify_OnChange;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader reader = cmd.ExecuteReader();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return Ok( );
}
//dependency******
private async void DependencyNotify_OnChange(object sender, SqlNotificationEventArgs e)
{
ChatNotification().Wait();
var dependency = sender as SqlDependency;
if (dependency == null) return;
if (e.Info == SqlNotificationInfo.Insert || e.Info == SqlNotificationInfo.Merge)
{
var chats = _dbContext.ChatMessage.FromSql(#"SELECT * FROM [dbo].[ChatMessage] " +
"WHERE IsSeenByAdmin=0").OrderBy(c => c.DateTime).ToList();
dependency.OnChange -= DependencyNotify_OnChange;
await _chatAdminHubContext.Clients.All.SendAsync("AdminListen",
chats);
}
}
public Startup(IConfiguration configuration)
{
SqlDependency.Start(dbConnectionStr);
Configuration = configuration;
}
the whole thing works with this connection string which is connected to my localdb:
private readonly string dbConnectionStr=
"Data Source=.;Initial Catalog=signalr;Integrated Security=True;user id=sa;password=******";
but it does not work if i change the connection string to this:
private readonly string dbConnectionStr=
"Data Source=server.*****.com\\MAININSTANCE;Initial Catalog=signalr;Persist Security Info=True;User ID=sa;Password=********";
i can connect to the server and local db with no problem, and can use fetching data with entityframework from both, the connection is made successfully yet the only problem is that when i insert row in localdb [dbo].[ChatMessage], dependency works but when i insert row in servers [dbo].[ChatMessage], it does not.
the only thing i did was to set broker enabled. Could it be related to any permissions on server's db?
UPDATE:
select * from sys.transmission_queue
gives this transmission_status:
An exception occurred while enqueueing a message in the target queue. Error: 15517, State: 1. Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission. 5

Unable to Connect SQL Server when using MultiThreading

I am try to connect SQL Server using multi-threading the execute SQL query on tables.
When I try to connect SQL server it's working fine without any issue, but when try to connect using thread mechanism it displaying exception.
Here is my code can exception message please let me know how to resolve this issue.
using System;
using System.Data.SqlClient;
using NUnit.Framework;
using System.Threading;
namespace ThreadSQLConnect
{
[TestFixture]
public class SQLConnect
{
private static object threadLock = new object();
[Test]
public void temp()
{CreateThread(1); }
public static void CreateThread(int ThreadCount)
{
Thread[] workerThread = new Thread[ThreadCount];
for (int i = 0; i < ThreadCount; i++)
{
workerThread[i] = new Thread(new ThreadStart(ConnectDBAndExecuteQueryWithLock));
workerThread[i].Name = i.ToString();
workerThread[i].Start();
}
}
public static void ConnectDBAndExecuteQueryWithLock()
{
lock (threadLock)
{
try
{
string sqlQuery = "insert into tblMasterLookup Values (" + Thread.CurrentThread.Name + ",'Test','2.0','Myapplication',GetDate())";
string connectionString = string.Format("Server={0}; Database = {1}; User Id = {2}; Password = {3};",
"serverNname",
"Databasename",
"ReadOnlyUser",
"ReadOnly12");
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch(Exception e)
{ Console.WriteLine(e.StackTrace); }
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.CommandTimeout = 80;
command.ExecuteNonQuery();
Console.WriteLine("Executed Thread.. " + Thread.CurrentThread.Name);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
Here is exception message

sqlite attach password protected database

How can I attach a password protected sqlite database to a non password protected database?
I have a user sqlite database that is not password protected.
I'm trying to attach a read-only resource database that is password protected.
I could reverse their roles and open the password protected first and attach the user database, but I think it should work this way?
I haven't tried too many things so there is no code to share. but I have googled and can't seem to find any mention of this in the documentation or any examples.
It's all about opening a password protected database directly.
Edit: - heres what i've tried...
using both https://www.sqlite.org/lang_attach.html https://www.sqlite.org/c3ref/open.html
private void btnPasswordAttach_Click(object sender, EventArgs e)
{
string pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Users #1.astc";
string connectionstring = string.Format("Data Source={0};Version=3;BinaryGUID=false", pathToUnProtected);
SQLiteConnection connection = new SQLiteConnection(connectionstring);
connection.Open();
TestQueryMain(connection); **//WORKS**
pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Mods #1.aste";
string commandTextUnProtected = string.Format("ATTACH DATABASE '{0}' AS mods", pathToUnProtected);
SQLiteCommand attachCommandUnProtected = new SQLiteCommand(commandTextUnProtected, connection);
attachCommandUnProtected.ExecuteNonQuery();
TestQueryUnProtected(connection); **//WORKS**
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite";
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
//string pathToProtected = #"file:C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite;password=VanillaIceCream;";
string password = "VanillaIceCream";
string commandText = string.Format("ATTACH DATABASE '{0}' AS vanilla", pathToProtected);
SQLiteCommand attachCommandProtected = new SQLiteCommand(commandText, connection);
attachCommandProtected.ExecuteNonQuery();
TestQueryProtected(connection); **//NO SUCH TABLE...**
}
private void TestQueryMain(SQLiteConnection connection)
{
string sql = "Select * FROM Notes";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteReader();
}
private void TestQueryProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from vanilla.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
private void TestQueryUnProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from mods.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
found the answer in another post:
https://stackoverflow.com/a/1385690/10099912
to attach a password protected sqlite database you need to use the 'key'word:
"ATTACH DATABASE 'C:\test.sqlite' AS attachedDb KEY 'password'"

Execute Reader is not returning a result

Can you please help me see what is wrong with my code? If I run the stored procedure using the a parameter for Id, I get a result in SQL Server. But when I use the code below using the same value for Id, in my if(rdr.HasRows).. I get a false.
public Student Find(int key)
{
string connectionPath = ConnectionStrings.DbConnection;
Student student = null;
try
{
using(var sqlCon = new SqlConnection(connectionPath))
{
sqlCon.Open();
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
{
cmd.Parameters.AddWithValue("#Id", key);
using(var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
if (rdr.HasRows)
{
while (rdr.Read())
{
student = new Student
{
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString(),
Gender = rdr["Gender"].ToString()
};
}
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return student;
}
If I try to get all records, I don't get any problems:
public IEnumerable<Student> GetAll()
{
var studentList = new List<Student>();
try
{
string connectionPath = ConnectionStrings.DbConnection;
using(var sqlCon = new SqlConnection(connectionPath))
{
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
{
sqlCon.Open();
using(var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
studentList.Add
(
new Student
{
Id = Convert.ToInt32(rdr["Id"]),
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString()
}
);
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return studentList;
}
This is using asp.net core
Your code for Find lacks the definition that this is a stored procedure that you're calling.
If you look at your GetAll, you have:
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
defining this SqlCommand to be a stored procedure - this setting is missing from your Find code:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
I'm pretty sure it'll work if you add that:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon) { CommandType = CommandType.StoredProcedure}))

Why do I get an exception when I reference DataGridView CurrentRow?

I'm trying to get a "changed currentcell" event in DataGridView, but every time I try to load the form (which is a child of another form), I get an exception in the datagridview_currentcell event:
SystemNullReferenceException: object not set to an instance of an object.
I guess it's because I haven't selected any row. Of course I can use catch and try to bypass, but I want a more elegant way and to know what am I doing wrong.
Here's my code:
Form2.CS:
namespace AsefotSystem
{
public partial class ownerReport : Form
{
public ownerReport()
{
InitializeComponent();
loadDB();
setGrid();
}
private void loadDB()
{
string connetionString = null;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
DataSet ds = new DataSet();
string sql2 = null;
connetionString = ConfigurationManager.ConnectionStrings["RiskDB"].ConnectionString;
sql2 = "select * From tbl2_asefot";
connection = new OleDbConnection(connetionString);
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(sql2, connection);
oledbAdapter.Fill(ds, "Asefot");
oledbAdapter.Dispose();
connection.Close();
dsAsefotGrid = ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void setGrid()
{
Controls.Add(dataGridView1);
dataGridView1.DataSource = dsAsefotGrid.Tables[0];
}
private void dataGridView1_CurrentCell(object sender, EventArgs e)
{
try
{
textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
DataSet dsAsefotGrid;
}
}
Form2.Designer.CS:
this.dataGridView1.CurrentCellChanged += new System.EventHandler(this.dataGridView1_CurrentCell);
Instead of the try{} catch{}, you could test if the CurrentCell or even CurrentRow is not null.
if(dataGridView1.CurrentCell != null)
{
textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString();
textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}
Your dataGridView Cell has no value and you are trying to save a string of null.
Try catching the exception and inform the user that he has to write something in the cell
try
{
textBox1.Text = dataGridView1.Rows[dataGridView1.
CurrentRow.Index].Cells[2].Value.ToString();
}
catch(NullReferenceException)
{
MessageBox.Show("You cannot process an empty cell");
}
Please find more information under the following link:

Resources