I use SqlDataAdapter and SqlCommandBuilder to perform DML transactions on rows in a SQL Server database.
I am able to add and delete multiple rows in database but update.
This is the code:
SqlDataAdapter da = new SqlDataAdapter(#"select top 1 * from " + tableName,
ConnectionString);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);
I'm trying to use AcceptChanges, so far it doesn't work.
This is how I usually do within C#. If you want to give this a try.
//you may put this as a direct string or in a static class when layering
//you can pass table as hard-coded value or as a parameter
String SqlQuery = "UPDATE " +
" [tableName] " +
" SET [Column1ToBeUpdated]=#Column1Value," +
" [Column2ToBeUpdated]=#Column2Value" +
" WHERE ([ColumnxWithCondition] = #Condition)";
//add OR, AND operators as per your needs
//choose the correct SqlDbType for your column data types
public bool UpdateMyTable(String SqlQuery, Someclass obj)
{
SqlCommand sCommand = new SqlCommand(this.SqlQuery, (new SqlConnection(ConnectionString)));
sCommand.Parameters.Add("#Column1Value", SqlDbType.VarChar).Value = obj.col1Value;
sCommand.Parameters.Add("#Column2Value", SqlDbType.VarChar).Value = obj.col2Value;
sCommand.Parameters.Add("#Condition", SqlDbType.VarChar).Value = obj.condition;
sCommand.Connection.Open();
var rowsAffected = sCommand.ExecuteNonQuery();
sCommand.Connection.Close();
return rowsAffected > 0;
}
//if you want to see the number, you may return rowsAffected
i have found reason, a column is set DateTime type. So, this Column isn't saving to the database.
Related
I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}
I have the following code:
SqlConnection con = new SqlConnection(#"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
String Query;
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
MessageBox.Show(" " + this.dataGridView1.Columns.Count);
MessageBox.Show(" " + this.dataGridView1.Columns[i].Name + " ");
MessageBox.Show(" " + this.dataGridView1.SelectedRows[0].Cells[i].Value + " ");
Query = "insert into [" + this.comboBox1.Text + "] ([" + this.dataGridView1.Columns[i].Name + "]) Values ('" + this.dataGridView1.SelectedRows[0].Cells[i].Value + "') ;";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(Query, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
}
con.Close();
It should insert a specific value into EVERY column of a table (shown in a dataGridView), but after it saves the first value (the value from the first column of the row that we want to insert) it refreshes the table and only that first value gets inserted... I want to insert the whole row
the code is behaving correctly as expected.
here is your code:
for each column
build sql string to take first row, current column and insert in db
create sql command using the above sql string
execute the above command
refresh datagrid
next
the above produces the exact behaviour you are experiencing, this is expected and correct in the sense that the code does exactly what it is told to do.
what your code should be based on your description:
for each row
build base sql statement
for each column
add current value and field name to the base statement
next
create sql command
fill the command with the statement built in the previous cycle
execute the sql statement
next
refresh datagrid
if you have to insert only one row then the outer foreach is not needed
while performing string concatenation to build the statements take care of input sanitization and datatypes.
con.open() should be outside the loop
Okay basically I have a SQL Server database that has details in it.
Column names: Student_Id, Student_name, Unit_number, Unit_grade
I would like to query this database using two textboxes where you enter the id and unit_number and it will return the results in a message box when a button is clicked.
Where the question marks in the code are is where I am unsure of how to display a message box with the result. Unless this is completely the wrong way of doing things, I am only starting out with SQL in C#
I shouldn't be prone to SQL Injection using parameters as far as I know?
try
{
string str = "SELECT * FROM Students WHERE (Student_Id, Unit_number LIKE '%' + #search + '%')";
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox1.Text;
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox2.Text;
connect.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataSet dataSet = new DataSet();
dataAdapt.Fill(dataSet, "Student_Id, Unit_number");
//?
//?
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your SQL is wrong in that your WHERE clause is syntactically incorrect. You probably want something like:
string str = "SELECT * FROM Students WHERE Student_ID = #id AND " +
"Unit_number LIKE #search";
This assumes that Student_ID is a text type. The syntax would be slightly different if it was a number.
You are trying to add the same parameter to the query twice, which you won't want. Instead you'd want two parameters to match with the new SQL definition:
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
Running ExecuteNonQuery on the SqlCommand object doesn't do much for you as it is a query and you're not asking for the result back.
If you're only expecting one table back from your query, you'd probably be better off with a DataTable rather than a DataSet (the DataSet can contain many tables which is overkill for what you need).
try
{
string str = "SELECT * FROM Students WHERE Student_Id = #id AND " +
"Unit_number LIKE #search";
connect.Open();
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataTable dataTable = new DataTable();
dataAdapt.Fill(dataTable);
// At this point you should have a DataTable with some results in it.
// This is not going to be the best way of displaying data,
// but it should show you _something_
// It just iterates through the rows showing the columns
// which you've shown as being in your data.
foreach (DataRow dr in dataTable.Rows)
{
MessageBox.Show(String.Format("{0} - {1} - {2} - {3}",
dr["Student_Id"], dr["Student_name"],
dr["Unit_number"], dr["Unit_grade"]));
}
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
EDITED to change the parameter handling as it didn't quite do what was needed. The % symbols are not part of the parameter rather than the SQL string.
Good day! I am having a hard time fixing this problem. I've been searching the answer for this but seemed to be very very hard to look for the most fitting answer.
i use this query to search for a tenant's name based on what the user inputs in the txtSearchRP textbox, it works very well to data with no apostrophe in it, however when the user searches for a name containing ' , it does not function well.
example: user inputs MAX'S to search MAX'S RESTAURANT
SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Thanks for your help in advance!
edit for more information:
I am actually passing the query to sqlDataSource to bind the gridview automatically after the user click THE BUTTON.
SqlDataSource3.SelectCommand = SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Try this
conn = new
SqlConnection("ConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT * from tenant WHERE (name LIKE #tenant)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "#tenant";
param.Value = "%" + txtSearchRP.Text + "%"; // you can use any wildcard operator
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
In addition to the answers already given, in some applications, you might need to consider escaping wildcards such as % in the input string provided by the user.
For example, if the user enters "25%", then matching on "%25%%" will return values that contain "25", rather than restricting to values that contain "25%".
You can escape wildcards as follows (for SQL Server):
string value = ... value entered by user;
value = value.Replace("[", "[[]");
value = value.Replace("_", "[_]");
value = value.Replace("%", "[%]");
Better way create storedprocedure
SP :
Create proc sp_Search( #txtSearch nvarchar(150))
as begin
SELECT * from tenant WHERE name like #txtSearch+'%'
end
Code behind :
string txtSearch = txtSearchRP.Text;
SqlDataReader dr;
using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = conn;
conn.Open();
dr = cmdd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
var name = dr["name"].ToString();
var location = dr["location"].ToString();
}
} dr.Close();
conn.Close();
}
}
Updated:
Write a function which returns datatable so that we can bind it to our gridview control as i did in code below
public DataTable bindGridView()
{
string txtSearch = txtSearchRP.Text;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
SqlCommand cmdd = new SqlCommand();
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = con;
con.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmdd);
DataSet ds = new DataSet();
dap.Fill(ds);
dt = ds.Tables[0];
con.Close();
}
return dt;
}
On Button click : Call bindGridView() function for binding Gridview control
GridView1.DataSource = bindGridView();
GridView1.DataBind();
thanks to all who shared their knowledge and effort, finally got the answer through the String replace method
HERE'S THE 3-LINED CODE
string value = txtSearchRP.Text;
value = value.Replace("'", "['']");
sqlDataSource3.SelectCommand = "SELECT * from tenant WHERE (name LIKE '%" + value.ToString() +"%')";
through the joined effort, answers you posted here, we solve the problem in the simplest form :)
I have two methods, one to insert, update and delete and a second is checking whether data already exists in my database or not. The main purpose of all code is that I don't want to insert duplicate data into the database.
public class DAL : System.Web.UI.Page
{
SqlConnection connection;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public int numofrows;
//Connection Method
public void Connection()
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
}
//This Method will Insert,Update and Delete in Database
public void InsertUpdateDelete(string query)
{
////connection = new SqlConnection("Data Source=IM-82B70624D72D;Initial Catalog=AppointmentScheduler;User ID=sa;Password=za3452432760za");
//connection = new SqlConnection(connectionString);
//connection.Open();
this.Connection();
cmd = new SqlCommand(query, connection);
numofrows = cmd.ExecuteNonQuery();
connection.Close();
}
//This Method will read data From Database
public DataTable ReadData(string Query)
{
this.Connection();
da = new SqlDataAdapter(Query, connection);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Data already Exist");
}
return dt;
}
}
I have to use both above code in index.aspx. How can I use both above code in index.aspx?
I tried to use but that is not working.
index.aspx code:
protected void btnSaveDays_Click(object sender, EventArgs e)
{
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id='" + DropDownListDays.SelectedValue + "'";
dal.ReadData(this.query);
this.query = "INSERT INTO Dayss VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
dal.InsertUpdateDelete(this.query);
Response.Write("Day Inserted Successfully");
}
But this code is not working and generating error
Conversion failed
not Day_Id is int, and Dayss have two columns. One is id and second is
name
Then there is no point to use single quotes with int typed column value. Single quotes is for character column values.
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id = " + DropDownListDays.SelectedValue ;
And if you want to insert just one column, you need specify your column name in your Dayss table like;
this.query = "INSERT INTO Dayss (YourColumnName) VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
Take a look INSERT (Transact-SQL)