Delete data in sql table using c# and present it in gridview - c#

I have the following method:
Connection c =new Connection();
SqlCommand cmd = new SqlCommand();
String empID = toolStripTextBox1.Text;
cmd.CommandText = "DELETE FROM tblEmployee WHERE employeeNumber='empID'";
cmd.Connection = c.con;
c.con.Open();
dataGridView1.CurrentCell = null;
int numberDeleted = cmd.ExecuteNonQuery();
MessageBox.Show(numberDeleted.ToString() + " employees were deleted.<br>");
c.con.Close();
I'm trying to delete a record in the table and update gridview to show the remaining records in the table. the code doesn't delete any record

This:
DELETE FROM tblEmployee WHERE employeeNumber='empID'
Should be converted to use a parametrized query in the following way:
cmd.CommandText="DELETE FROM tblEmployee WHERE employeeNumber=#id";
The reason is that your previous statement was simply concatenating the delete from ... part with the string 'empid' which I assume is not what you want. You are after something like this:
delete from ... where employeeNumber={some_number} where some_number is a parameter
In order to pass a parameter to your SQL Statement you do this:
cmd.Parameters.AddWithValue("#id",empID);//I assume empID is a variable containing an ID
cmd.ExecuteNonQuery();
If you want the change immediately reflected on your grid, you need to select the data again and rebind your grid.

The problem is that probably no empID with the value 'empID' exists..
You didn't put the value of the empID in the command, but added an exact string of 'empID', which cannot be found in your table.
Put the empID value as a parameter like Icarus advised.

Related

Insert a value in a table from another table using a variable in C# , SQL Server

I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

What method can be used to specifically insert data into your C# DataGridView from SQL?

Problem:
Code works fine, however, when I launch my program my two predefined columns Course_ID and File_Count are present in my then blank dataGridView. There is also an empty default row.
Whenever I run my query, my dataGridView is getting an extra column created and an extra row created. The result from the query goes into this new third column on the first row which is weird.
See here:
http://imgur.com/UBFI8Nz
Here is my code:
string[] courses = txtBoxCourses.Text.Split(',');
SqlConnection myConnection = new SqlConnection("user id=userid;" +
"password=password;server=myserver;" +
"Trusted_Connection=no;" +
"connection timeout=30");
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
myCommand.Connection = myConnection;
DataTable t = new DataTable();
foreach (string line in courses)
{
myCommand.CommandText = "DECLARE #CourseName varchar(80); Set #CourseName = '"+line+"' SELECT COUNT(*) FROM ( SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;";
adapter.Fill(t);
dataGridView1.DataSource = t;
}
What I want to happen is I want to fill in the first column with the values from my string[] courses list and I want it to correspond with the result from the query in my foreach statement. For example, if I use two course IDs to query, test1 and test2 I'd prefer this:
Course_ID file_count
test1 234
test2 1478
I've looked into using the DataPropertyName property but I don't think that's it.
Try changing your select to:
SELECT #CourseName as Course_ID, COUNT(*) as File_Count FROM (
SELECT FILE_ID,PARENT_ID ,PATH_ID,FULL_PATH ,FILE_NAME FROM BBLEARN_cms_doc.dbo.XYF_URLS
WHERE FULL_PATH like '/courses/'+#CourseName+'/%') as subquery;
Your current query is returning an integer and your grid view doesn't see it attached to any of your predefined columns. Try aliasing the columns with the column name in the grid view. That should tie your sql results to your current columns.

SQL Server database last_rowID

I have a C# app with have to use SQL Server database with 1 table (All_Data) and 5 columns (ID, Name, Surename, Age,Location)
Before inserting a new row how can I find out or get the value of the last ID in the table
I have a following code but it,a not work well
string query = "SELECT MAX(ID) FROM All_Data";
SqlCommand comSelect;
comSelect = new SqlCommand(query, connection);
int ID = (int)comSelect.ExecuteScalar();
ERROR message:
ExecuteScalar: Connection property has not been initialized
Please help me
First, from your code it is not clear what is the value of the variable connection.
From the error message it seems that you don't have initialized this variable and thus you get the error. (connection = new SqlConnection(....);)
However, this is not the correct way to handle this scenario.
You need to make the ID column an IDENTITY column and then don't try to retrieve its value before executing any INSERT.
An IDENTITY column receives its value directly from the database when there is a new record to insert. And letting the database code work on this data it is the best option if you want to be safe from concurrency issues.
If you need to retrieve the ID value after an INSERT query because you need it as a Foreign Key in other tables or for your own code, then you could simply use the T-SQL command
SELECT SCOPE_IDENTITY()
For example, suppose you have to insert a record in that table, and you want to know the IDENTITY value assigned to the ID column
string query = #"INSERT INTO All_Data(Name,Surename,Age,Location)
VALUES(#name, #surname, #age, #loc);
SELECT SCOPE_IDENTITY()";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("#name", yourNameValue);
.... other parameters ...
int newID = Convert.ToInt32(cmd.ExecuteScalar());
}
As you can see, this code doesn't try to pass a value for the ID column. It pass just the other fields with a parameterized query. But at the end of the first query there is a call to SELECT SCOPE_IDENTITY() and this returns whatever value the database has assigned to the column ID (of course you should have set the IDENTITY property on the field).
This will work correctly in multiuser and concurrent scenario
The error fires when the command doesn't have a connection. Please check connection is open.
Error saysExecuteScalar: Connectio property has not been initialized
double Check your connection string whether it is defined properly. You can check here to know how to define connection string.
you have not opened connection so open it before use :
comSelect = new SqlCommand(query, connection);
connection.Open();
int ID = (int)comSelect.ExecuteScalar();
connection.Close();

Inserting a List<> into SQL Server table

I have an entity Report whose values I want to insert into a database table. The following attributes of Report have to be inserted:
reportID - int
RoleID - int
Created_BY = SYSTEM(default)
CURRENT_TIMESTAMP
Now the problem is with the 2nd attribute. I have a report with the LIST<ROLES> attributes. ROLES is a well defined entity which has an ID and a NAME. From this list I have to extract every role and insert each role's ID into the table.
So my query presently looks as below :
INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
VALUES({0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP)
The C# code from where I am parsing these values is as follows :
try
{
StringBuilder _objSQL = new StringBuilder();
_objSQL.AppendFormat(Queries.Report.ReportQueries.ADD_NEW_ROLES, report.ID, "report.MarjorieRoles.Add(MarjorieRole"));
_objDBWriteConnection.ExecuteQuery(_objSQL.ToString());
_objDBWriteConnection.Commit();
_IsRolesAdded = true;
}
So please guide me how to add roles from C# function
I'm assuming you say SQL (structured query language) and you really mean Microsoft SQL Server (the actual database product) instead - right?
You cannot insert a whole list as a whole into SQL Server - you need to insert one row for each entry. This means, you need to call the INSERT statement multiple times.
Do it like this:
// define the INSERT statement using **PARAMETERS**
string insertStmt = "INSERT INTO dbo.REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED) " +
"VALUES(#ReportID, #RoleID, 'SYSTEM', CURRENT_TIMESTAMP)";
// set up connection and command objects in ADO.NET
using(SqlConnection conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn)
{
// define parameters - ReportID is the same for each execution, so set value here
cmd.Parameters.Add("#ReportID", SqlDbType.Int).Value = YourReportID;
cmd.Parameters.Add("#RoleID", SqlDbType.Int);
conn.Open();
// iterate over all RoleID's and execute the INSERT statement for each of them
foreach(int roleID in ListOfRoleIDs)
{
cmd.Parameters["#RoleID"].Value = roleID;
cmd.ExecuteNonQuery();
}
conn.Close();
}
let say lstroles is your LIST<ROLES>.
lstroles.ForEach(Role =>
{
/* Your Insert Query like
INSERT INTO REPORT_MARJORIE_ROLE(REPORT_ID, ROLE_ID, CREATED_BY, CREATED)
VALUES(REPORT_ID, Role.ID, {0}, {1}, 'SYSTEM', CURRENT_TIMESTAMP);
Commit you query*\
});
On a personal note: Beware of SQL Injection.

How can i get the ##IDENTITY returned from a INSERT from MySQL (2008) using C# [duplicate]

Using C# in Visual Studio, I'm inserting a row into a table like this:
INSERT INTO foo (column_name)
VALUES ('bar')
I want to do something like this, but I don't know the correct syntax:
INSERT INTO foo (column_name)
VALUES ('bar')
RETURNING foo_id
This would return the foo_id column from the newly inserted row.
Furthermore, even if I find the correct syntax for this, I have another problem: I have SqlDataReader and SqlDataAdapter at my disposal. As far as I know, the former is for reading data, the second is for manipulating data. When inserting a row with a return statement, I am both manipulating and reading data, so I'm not sure what to use. Maybe there's something entirely different I should use for this?
SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.
using (var con = new SqlConnection(ConnectionString)) {
int newID;
var cmd = "INSERT INTO foo (column_name)VALUES (#Value);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, con)) {
insertCommand.Parameters.AddWithValue("#Value", "bar");
con.Open();
newID = (int)insertCommand.ExecuteScalar();
}
}
try this:
INSERT INTO foo (column_name)
OUTPUT INSERTED.column_name,column_name,...
VALUES ('bar')
OUTPUT can return a result set (among other things), see: OUTPUT Clause (Transact-SQL). Also, if you insert multiple values (INSERT SELECT) this method will return one row per inserted row, where other methods will only return info on the last row.
working example:
declare #YourTable table (YourID int identity(1,1), YourCol1 varchar(5))
INSERT INTO #YourTable (YourCol1)
OUTPUT INSERTED.YourID
VALUES ('Bar')
OUTPUT:
YourID
-----------
1
(1 row(s) affected)
I think you can use ##IDENTITY for this, but I think there's some special rules/restrictions around it?
using (var con = new SqlConnection("connection string"))
{
con.Open();
string query = "INSERT INTO table (column) VALUES (#value)";
var command = new SqlCommand(query, con);
command.Parameters.Add("#value", value);
command.ExecuteNonQuery();
command.Parameters.Clear();
command.CommandText = "SELECT ##IDENTITY";
int identity = Convert.ToInt32(command.ExecuteScalar());
}

Categories