delete data on SQL table based on datatable input [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This method below goes into a table and deletes all of the table. But in the datatable "table" below in the first column there are dates which i would like to be deleted from the database. how would i go about doing this
Datatable table = new DataTable()
string sqlConnectionString =
"Server = 100.720.8.196; Database = testDat; User Id = sa; Password = ";
// Copy the DataTable to SQL Server
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
string deleteSting =
"delete from dbo.testTable where clientId=1212";
conn.Open();
using (SqlCommand cmd = new SqlCommand(deleteSting, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}

I'm just guessing here, you probably mean to make the date column empty. If that's the case then you use UPDATE, like:
string updateString =
"UPDATE dbo.testTable SET datecol = #datecol where clientId=#clientID";
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateString, conn))
{
cmd.Parameters.Add("#datecol", SqlDbType.Date).Value = DbNull.Value;
cmd.Parameters.Add("#clientID", SqlDbType.Int).Value = 1212;
cmd.ExecuteNonQuery();
}
conn.Close();

Well, there are a few options. You could loop through your table and create a string containing your dates in a comma separated list. With that, you can create a SQL Statement like delete from table where dateCol in (date1, date2, date3, etc...)
Or you could just loop through your data table, and do one delete per loop iteration. Either way will work.
However you decide to proceed, make sure to use parameters instead of string concatenation to prevent issues like SQL Injections:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

Related

Search database for value and get info c# Forms [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a database called "users" where user information is saved. When you login with your name and pass, your name is send to the homeform, where i want to get the "to-do list" that's saved in the database with your info. Here's my code so far:
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM `user` WHERE `username`=#username AND `todo`=#todo";
So basically i need to get the todo of the user (which is sent to this form as _name) lets say admin, and display it in tbTodo.
if it is in the same form you can try using
select `user`.todo from `user` where `username` = #username
considering username is unique
If the main problem is parameters - u can use property Parameters:
cmd.Parameters.AddWithValue("#username", user);
There is an example in msdn:
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

C# How to get DataTable value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I still new to C# and just have 3 months plus of learning process. I would like to seeking advice on how to extract data value from my DataTable I have create for validation checking.
private void checker
{
string sqlSelect2 = "SELECT a.AccNo, a.CompanyName , a.CreditLimit, FROM Debtor a JOIN";
}
which i have named TableCehecker, i do not need to put it to gridview, just for checking purposes.
In the private void process how can I extract dataTable TableCehecker and the value?
Thank you,
Brian
You need to follow the Docs from MSDN:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
You can then check whatever you want of data inside the DataTable either by querying or by looping through the rows and checking the column values.
Based on your comments, to extract values from single row:
DataRow drow = dt.Rows[0];
string value = drow.Field<string>("CompanyName");

Error when trying to insert data to multiple table [C# Winform SQL Server] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Getting the following error when tried inserting data in multiple tables.
Incorrect syntax near the keyword 'User'
Button Click Code:
private void buttonSave_Click(object sender, EventArgs e) {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleTest1.Properties.Settings.SampleTestDBConnectionString"].ConnectionString);
SqlCommand cmd = conn.CreateCommand();
try {
UserId = UserId + 1;
cmd.CommandText = "INSERT INTO [User](User_Id,Name,Gender,Is_Active,Created_Date,Activated_Date) values(#userid,#name,#gender,#isactive,#createdate,#activedate)";
conn.Open();
cmd.Parameters.AddWithValue("#userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = textBoxName.Text;
cmd.Parameters.AddWithValue("#gender", SqlDbType.VarChar).Value = textBoxGender.Text;
cmd.Parameters.AddWithValue("#isactive", SqlDbType.Bit).Value = "True";
cmd.Parameters.AddWithValue("#createdate", SqlDbType.Date).Value = System.DateTime.Today;
cmd.Parameters.AddWithValue("#activedate", SqlDbType.DateTime).Value = System.DateTime.Now;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "INSERT INTO User_Details(User_Id,Mobile,Address,Job_Contract) values(#userid,#mobile,#address,#jobcontract)";
cmd.Parameters.AddWithValue("#userid", SqlDbType.Int).Value = UserId;
cmd.Parameters.AddWithValue("#mobile", SqlDbType.VarChar).Value = textBoxMobile.Text;
cmd.Parameters.AddWithValue("#address", SqlDbType.VarChar).Value = textBoxAddress.Text;
cmd.Parameters.AddWithValue("#jobcontract", SqlDbType.VarChar).Value = textBoxJobContract.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
I have declared UserId value as
static int UserId = 100;
Not sure what went wrong. Please do comment if more details required.
REFERENCES:
LINK 1 : ASP.NET C# Insert data into multiple table
LINK 2 : Insert into two tables at once.
LINK 3 : Getting Syntax error in Insert statement
LINK 4 : Insert Data into two tables simultaneously in SQL Server
User is reserved keyword so you need to use it like below
Insert into [User] (columns) values (#Values);
Hope it helps!
Well, its the database design logic where I finally tried solving this problem.
I used most of the suggested edits in comments as dbo.[User], [User] and [SampleTestDB].[dbo].[User]in INSERT INTO statement.
Tried with usingstatements and changed AddWithValueto Add
Tried using a transaction query to insert into [User]table and then [User_Details]table.
Of course, tried cleaning up and rebuild the solution as I was using multiple instance and versions of Visual Studio at same time.
ISSUE:
I declared the User_Id in the [User]table as Primary,NOT NULL,Unique
and in [User_Details]table as Primary,NOT NULL and used auto-incremental index.
In the button-click code, I just used static int which conflicted the INSERT statement of [User]table as it contained Unique property.
SOLUTION:
Solved the problem by droping and recreating the [User] table with User_Id contraints same as [User_Details] table.
(Removed Unique constrain in [User] table)

Alert message when certain limit has been made [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am creating a form for alerting the user that the stock for this item in the database is getting the limit or passed right through the limit.
this is my code for checking the quantity of a certain stock
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from tbl_BloodChemistry where Glucose = "+123+" ";
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
It's not actually the answer, but you have no reason to retrieve all data to collect count of rows. Use SQL COUNT and ExecuteScalar() for this.
Also, it's important to use command Parameters to your query. Don't ever build a query in your way! The input variable, Glucose, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as appropriate.
Assign the SqlParameter object to the SqlCommand object's Parameters property.
var glucoseFilterValue = "123";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from tbl_BloodChemistry where Glucose = #Glucose";
cmd.Parameters.AddWithValue("#Glucose", glucoseFilterValue);
var count = (int) cmd.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
Then you'll make your code more clean and prevent extra loading to your communication channel.

Missing Rows Property in SqlDataReader [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public bool ValidateUser(string uName)
{
SqlCommand cmd = new SqlCommand();
if (connection == null)
{
connection = connectToDB();
}
cmd.Connection = connection;
cmd.CommandText = "Select * from Users where UserName='" + uName + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
I wrote the code in my data access layer but it was giving error on rows to count the columns.
Error:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)
Use HasRows instead because SqlDataReader doesn't have a property call Rows.
if (dr.HasRows)
{
return true;
}
However, if you want the count instead you may load it into a datatable
DataTable dt = new DataTable();
dt.Load(dr);
int num = dt.Rows.Count;
SqlDataReader does not have a Rows Property.
Perhaps consider the HasRows property of SqlDataReader
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.hasrows.aspx
There is no Rows property in an SqlDataReader.
But your code has many problems.
I would change your code in this way:
public bool ValidateUser(string uName)
{
using(SqlConnection cn = connectToDB())
using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where UserName=#name", cn))
{
cmd.Parameters.AddWithValue("#name", uName);
return (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
}
}
The connection object is no more global and it is destroyed in
closing of the using statement.
No need to use a DataReader just to find out if the user exists or
not
Using a parameterized query to avoid SQL Injection on the input data
Avoid a global connection object. There is the connection pooling infrastructure that removes any performance problem and you are safe from excessive resource usage.
The SqlDataReader is a good choice when you need to retrieve sequentially a lot of records, but to get just the information if the user exists or not the best approach is through the ExecuteScalar method and an appropriate sql.
The parameterized query is a must for every serious database work. It will pass the work to format your input to the framework and you don't risk an Sql Injection

Categories