c# How to insert textbox value and save it to sql database? - c#

How to insert textbox value and save it to sql database?
I need some help here regarding to the question above. When I clicked button save, it should update the input textbox to the sql database Workers. Could you guys make some coding sample to achieve this? Because what I do is not working at all. This is the coding :
private void btnSave_Click(object sender, EventArgs e) {
#region SaveButton
// System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter ();
//System.Data.SqlClient.SqlCommandBuilder cb;
//cb = new System.Data.SqlClient.SqlCommandBuilder (da);
//add to Dataset a new row
DataRow dRow = ds1.Tables["Workers"].NewRow();
//add data to the new row just have been created
//refer to first_Name
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
dRow[3] = textBox3.Text;
//add command
//add to table worker a new row that declared by row variable name dRow
ds1.Tables["Workers"].Rows.Add(dRow);
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
//call data adapter da to update and save data into database sql server
//da.Update(ds1, "Workers");
MessageBox.Show("Entry Added!");
#endregion
con.ConnectionString = "Data Source=.\\SQLEXPRESS; AttachDbFilename =D:\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
string strSQL = "INSERT INTO Workers (first_Name, last_Name, job_Title )" + " VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', " + " '" + textBox3.Text + "') ";
con.Close();
}

I have solved this question by connecting properly to the Workers database. YeaY!!
Here's the right code for this question:
private void btnSave_Click(object sender, EventArgs e)
{
#region SaveButton
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tblWorkers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder (da);
//add to Dataset a new row
DataRow dRow = ds1.Tables["Workers"].NewRow();
//add data to the new row that has just been created
//refer to first_Name
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
dRow[3] = textBox3.Text;
//add command
//add to table worker a new row that declared by row variable name dRow
ds1.Tables["Workers"].Rows.Add(dRow);
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
//call data adapter da to update and save data into database sql server
da.Update(ds1, "Workers");
MessageBox.Show("Entry Added!");
con.Close();
#endregion

You'll need to Execute non query
Source
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}

Related

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#SSN"

I am developing a Windows Forms application in C#. I have always encryption columns in SQL Server.
My goal is to pull data from the datagridview in the form and display data.
I want to pull the data with the where operator and display it in the datagridview, but I am getting the following error.
Is there any way to do this?
I would be glad if you help!!
Error
System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#SSN".
Code:
private void btnSearch_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source = " + IP + "; Initial Catalog = " + db + "; Persist Security Info = False; User ID = " + username + "; Password = " + password + ";Column Encryption Setting = Enabled;");
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE TEST_TYPE = #SSN";
SqlParameter paramSSN = cmd.CreateParameter();
paramSSN.ParameterName = #"#SSN";
//paramSSN.ParameterName = "#SSN";
paramSSN.DbType = DbType.AnsiStringFixedLength;
paramSSN.Direction = ParameterDirection.Input;
paramSSN.Value = "'INITIAL_TEST'";
paramSSN.Size = 18;
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}
}
When I changed my code like this, the error went away.I found the solution.
ConnectionString();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE "+comboBox1.Text+" =
#SSN";
SqlParameter paramSSN = cmd.CreateParameter();
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
dataAdapter.SelectCommand.Parameters.Add("#SSN",
SqlDbType.VarChar,18).Value = textBox2.Text;
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}

Inserting records to MSAccess

Can someone explain to me why it wont allow me to insert my record into MS Access?
for some reason i have tried everything that is humanly possible but it wont let me do what i need to do. what i need to do is allow record to be written from my c Sharp program and would want to press a button which will insert the value into my MS Access.
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO BookKey, Title, Pages from Books;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds, "Books");
conn.Close();
DataTable dt = ds.Tables[0];
//define a new record and place it into a new DataRow
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
//add the new DataRow to DataTable
dt.Rows.Add(newRow);
//update DB
adapter.Update(ds, "Books");
//accept changes
ds.AcceptChanges();
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
An OleDbDataAdapter need a SELECT query and an OleDBCommandBuilder to generate automatically the INSERT/UPDATE/DELETE commands that will be used in the Update method
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "SELECT * FROM Books;";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
// See comments below for these properties
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
conn.Open();
adapter.Fill(ds, "Books");
DataTable dt = ds.Tables[0];
DataRow newRow = dt. NewRow();
newRow["BookKey"] = txtBookKey.Text;
newRow["Title"] = txtTitle.Text;
newRow["Pages"] = txtPages.Text;
dt.Rows.Add(newRow);
builder.GetInsertCommand();
adapter.Update(ds, "Books");
}
//update listBox1
lstDisplayBooks.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
lstDisplayBooks.Items.Add(row["BookKey"] + " " + row["Title"] + " (" + row["Pages"] + ")");
}
txtBookKey.Enabled = false;
txtBookKey.Text = " ";
txtTitle.Enabled = false;
txtTitle.Text = " ";
txtPages.Enabled = false;
txtPages.Text = " ";
btnInsert.Enabled = false;
}
The example in the link for the OleDbCommandBuilder contains an example like this.
The code should fix your initial error, but really there is no need to use an OleDbDataAdapter in this scenario. If your only objective is just to add a new record to the datatable and you don't need to maintain a local datasource like a DataGridView it is a lot simpler to use directly the OleDbCommand with an appropriate written INSERT and parameterized query
void Insert_Record(object s, EventArgs e)
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + #"data source =BookCSharp.accdb";
string dbcommand = "INSERT INTO Books (BookKey, Title, Pages) VALUES(?,?,?);";
using(OleDbConnection conn = new OleDbConnection(dbconnection))
using(OleDbCommand comm = new OleDbCommand(dbcommand, conn))
{
conn.Open();
comm.Parameters.AddWithValue("#p1", txtBookKey.Text);
comm.Parameters.AddWithValue("#p2", txtTitle.Text);
comm.Parameters.AddWithValue("#p3", txtPages.Text);
comm.ExecuteNonQuery();
}
.....

SQL Row Updating Not Working in C#

I can't figure out why the following code is not updating either my GridView nor my MySQL Database. Can anyone offer me some tips as to what I may be doing incorrectly?
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
connection();
GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
dr = com.ExecuteReader();
GridView1.EditIndex = -1;
bind();
}
Here is my bind method as requested:
private void bind()
{
connection();
string query = "select * from employeeDB where [Last Name:] like'" + TextBox1.Text + "%'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Replace
dr = com.ExecuteReader();
with
com.ExecuteNonQuery();
ExecuteReader is for SELECT queries.
Also, in real world application you should not build sql string like you do. Use SqlParameter instead to avoid sql injection and many other errors.
GridViewRow row = GridView1.Rows[e.RowIndex];
Label lblID = (Label)row.FindControl("lblID");
TextBox textName = (TextBox)row.Cells[3].Controls[0];
TextBox textadd = (TextBox)row.Cells[4].Controls[0];
TextBox textc = (TextBox)row.Cells[5].Controls[0];
/*are you sure column names are like [First Name:],[Last Name:] and [Email:] in the table*/
/*Syntax for update command should be like this "UPDATE TableName SET ColumnName1=#Parameter1, ColumnName2=#Parameter2 ....
* WHERE ColumnName=#ParameterName"
*/
String query = "update employeeDB set [First Name:]=#FirstName, [Last Name:]=#LastName, [Email:]=#Email where id=#id";
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = textName.Text;
com.Parameters.Add("#LastName", SqlDbType.VarChar).Value = textadd.Text;
com.Parameters.Add("#Email", SqlDbType.VarChar).Value = textc.Text;
com.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(lblID.Text) + 1;
con.Open();
com.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}
you should be doing something like this
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = TaskGridView.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
What are you getting now? Exception or just no error and nothing is happening? Things to check are db connection string-make sure your connection string is pointing to the db you are targeting. And second i would like to point out that the query is open for sql injection attack (something you need to consider - if you are going to use it to production code).Third, what do you have in the bind method? What data source its trying to bind and with what control? From the sample code itself, it looks like no data is being returned from db.
Updated with:
And by the way, should the colon be there in your query? See for instance the colon after first name ([First Name:] ) String query = "update employeeDB set [First Name:]='" + textName.Text + "', [Last Name:]='" + textadd.Text + "', [Email:]='" + textc.Text + "' where id='" + lblID + 1 + "'";

Using ExecuteReader instead of SQLDataAdapter

I've got a C# project where I'm trying to export the results of a datagrid. Sometimes the data gets quite large, so rather than re-executing the code I want to dump the dataset into a session variable.
This works perfectly in most of my projects. One example from a project where I use this is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
//Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");
//string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
//string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
//sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
//sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(DISTINCT Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
sqlquery = sqlquery + "from (SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM ClosedClaims_MERGE ";
sqlquery = sqlquery + "UNION SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM tblAuditing) CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "WHERE CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "' ";
sqlquery = sqlquery + "GROUP BY Spare, PROC_NM, AdminLevel ";
sqlquery = sqlquery + "ORDER BY Count(Claim_ID) DESC";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "dsEffVol");
// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSEffVol"] = ds;
// Perform the binding.
grdEffVol.Attributes.Add("style", "overflow:auto");
//GridView_WODetails.Attributes.Add("style", "table-layout:fixed");
grdEffVol.AutoGenerateColumns = true;
grdEffVol.DataSource = ds;
grdEffVol.DataBind();
}
I've got a new project where I'm not using SQL strings, but instead I'm pulling data based on SQL Server Stored Procedures. The code block there is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from RM_tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
string MyUseDates = DT1[4].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;
//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}
else
{
}
try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
GridView_Reports.DataBind();
// Add this to a session variable so the datagrid won't get NULLed out on repost
GridView_Reports.DataBound += GridView_Reports_RowDataBound;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
Console.WriteLine(ex);
return;
}
finally
{
connection2.Close();
connection2.Dispose();
}
}
}
}
}
}
I'm kind of guessing my way through this, and I'm not sure if I'm reading the data into a dataset properly. The page is shutting down, and I'm pretty sure the problem is in the lines:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Quite honestly, I've googled SqlDataReader vs SqlDataAdapter and can't really find anything, but I need to fill the session variable in the second example and also have the datagrid populate properly. So, in essence, I need to put the results of a Stored Procedure into a dataset. Can anyone offer suggestions on what I'm doing wrong?
I'm pretty sure most controls don't accept readers in their DataSource property. Plus the majority of readers are forward-only, so although you're trying to store the reader as a session variable, chances are you would only be able to read it once.
Why do you want to use a reader for this when your post seems to indicate that you know you need to use a DataSet? Why not just use an adapter the way you show in your first post? Adapters work fine with commands that use sprocs.
Instead of:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Just use:
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");
Session["SSRptMenu"] = ds;
GridView_Reports.DataSource = ds;

How duplicate entries be prevented while using SqlBulkCopy?

I am importing excel data into sql server using SqlbulkCopy, but the problem is i want to prevent any duplicate records being entered. Is there a way by which duplicate can be ignored or deleted automatically?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
var command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch
{
}
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable";
r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
Can this problem be fixed by creating a trigger to delete duplicates? if yes how? i am a newbie i have never created a trigger.
Another problem is no matter what i try i am unable to get column mapping to work. I am unable to upload data when column names in excel sheet and database are different.
You can create INDEX
CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY
And when you will insert data with bulk to db, all duplicate values will not inserted.
no, either you manage it on your dr object on you code before you load it into the db (like running a DISTINCT operation) or you create a trigger on the DB to check. The trigger will reduce the bulk insert's performace though.
Another option would be to bulk insert into a temp table and then insert into your destination table FROM your temp table using a select DISTINCT
as far as I remember,
you could filter out the redundant rows when importing from the excel file itself.
the following SQL query should be used in the OleDbCommand constructor.
var command = new OleDbCommand("Select DISTINCT ID,Data FROM [Sheet1$]", connection);

Categories

Resources