Query string to call up row data from SCOPE_IDENTITY - c#

I've got a submission page for users to input data. Then I redirect to a view page so they can view their input. Sessions are out, since this would be a high volume site, but I used the scope identity method at the end of my submission command. How do I query the scope ID value so that the row data is displayed in my view page?
Code is below: it's a training project, and I was expressly forbidden to parameterize in the interest of simplicity. But yes, I know paramaterizing is the way to go.
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String thisQuery = "INSERT INTO ProductInstance (CustId, CustName, SicNaic, CustAdd, CustCity, CustState, CustZip, BroId, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments) VALUES ('" + TextBox19.Text + "', '" + TextBox1.Text + "', '" + RadioButtonList1.SelectedItem + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + DropDownList1.SelectedItem + "', '" + TextBox4.Text + "', '" + TextBox18.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + DropDownList2.SelectedItem + "', '" + TextBox8.Text + "', '" + DropDownList3.SelectedItem + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox20.Text + "','" + TextBox14.Text + "','" + TextBox15.Text + "','" + TextBox16.Text + "'); SELECT SCOPE_IDENTITY() AS [lastInsertedProductId]";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand command = new SqlCommand(thisQuery, sqlConn))
{
int lastInsertedProductId = Convert.ToInt32(command.ExecuteScalar());
}
}
Response.Redirect("~/View.aspx");
and then the view page code is here:
protected void Page_Load(object sender, EventArgs e)
{
string x = Request.QueryString["ProductId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string editQuery = "SELECT CustId, CustName, SicNaic, CustCity, CustAdd, CustState, CustZip, BroName, BroId, BroAdd, BroCity, BroState, BroZip, EntityType, Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments FROM ProductInstance WHERE ProductId =" + x;
using (SqlConnection editConn = new SqlConnection(connectionString))
{
editConn.Open();
using (SqlCommand command = new SqlCommand(editQuery, editConn))
{
SqlDataReader dr = command.ExecuteReader();
dr.Read();
Label6.Text = dr.GetInt32(0).ToString();

Try moving lastInsertedProductId up in scope and
Response.Redirect("~/View.aspx?ProductId" + lastInsertedProductId );
But seriously, look into parameterized statements and http://bobby-tables.com/

You would make a stored procedure which does the work and in there you would get the SCOPE_IDENTITY.
Right after your insert.

Related

How to insert Persian words into a SQL Server database?

I am just wondering how to insert Persian characters into my service-based database?
When I save my data it shows something like '???'.
I have checked such questions like this. But, the solutions were not useful.
private void button1_Click(object sender, EventArgs e)
{
objConnection.Open();
if (ctypeCheckBox.Checked == true)
st = 1;
else if (ctypeCheckBox.Checked == false)
st = 0;
string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted!");
objConnection.Close();
}
Two things:
Never ever combine your query string with values
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
Should be immediately replaced with
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime)
VALUES(#cname, #cid, #ccredit, #csession, #st, #cstartDateDate, #cendDate, #cStartTime, #cEndTimeB)";
and then you should use
SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
for all parameters. This will save you from a lot of problems including SQL injection.
In the database your columns should have nvarchar data type.
Good luck
You should use SqlParameter .Giving example of only one parameter.You can add others as same way.
string query = "INSERT INTO LectureTable(Cname) VALUES(#name)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#name", cnameTextBox.Text);
param.SqlDbType = SqlDbType.String;
cmd.Parameters.Add(param);
.....
}

Insert checkbox value into database SQL

I want to insert the value of a checkbox into the database.
But in the database the column is null.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NAWAF;Initial Catalog=waterreport;Integrated Security=True");
con.Open();
if (checkBox1.CheckState == CheckState.Checked)
{
string chkek = "finish";
}
SqlCommand tump;
SqlCommand orugg;
string tmp = " UPDATE reportonetmp set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "' WHERE no like '" + label13.Text + "'";
tump = new SqlCommand(tmp, con);
tump.ExecuteNonQuery();
string org = " UPDATE reportone set finish_repair_date='" + textBox1.Text + "', finish_repair_hour='" + textBox2.Text + "', ca_of_problem='" + comboBox1.Text + "', line_type='" + comboBox2.Text + "', situation='" + textBox3.Text + "', diameter_of_pipes ='" + comboBox3.Text + "', timenoww3 ='" + label7.Text + "',checkk ='" + chkek + "' WHERE no like '" + label13.Text + "'";
orugg = new SqlCommand(org, con);
orugg.ExecuteNonQuery();
con.Close();
}
Aside from other problems (like having non-parametrised queries), are you sure that your DB column is called 'checkk'?
If that's correct, I would convert that DB column into a bit one (if you're using SQL Server) or boolean and updating it like this, instead of using an string variable:
"',checkk ='" + checkBox1.Checked
put oncheckchanged on checkbox control in aspx page and if checked means set values to 1 else 0(put if condition in checkedchanged event, so simple).same way you can get from database if value 1 means checkbox ID.Checked like this enough

Error converting data type varchar to numeric in c# program

Please Help me out,This is my database table in sql-server
(empcode varchar(50)
firstname varchar(50)
lastname varchar(50)
gender varchar(50)
address varchar(50)
contactno numeric(18, 0)
bloodgroup varchar(50)
dateofbirth date
country varchar(50)
qid varchar(50)
passportno varchar(50)
passportexpiredate date
designation varchar(50)
doj date
doexpid date
pf_acc_no numeric(18, 0)
agreementstartdate date
agreementenddate date
department varchar(50)
basic_sal numeric(18, 0)
remarks varchar(50)
empimage image)
and I'm Trying to insert my data through c# windows forms but i'm getting error as "Error converting data type varchar to numeric."
Here below is my c# code
private void button2_Click(object sender, EventArgs e)
{
cn.Open();
if (!empid())
{
DialogResult d = new DialogResult();
d = MessageBox.Show("Do You Declare Yourself All The Information Of This Employee Is Correct To Save?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (d == DialogResult.Yes)
{
int i = 0;
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "','" + txtcont.Text + "','" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', '" +
txtqibacc.Text + "', '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "','" + txtnetsalary.Text + "','" + txtremark.Text + "',#empimage) ", cn);
MemoryStream stream = new MemoryStream();
pb1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
cmd.Parameters.AddWithValue("#empimage", pic);
i = cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted Employee Record" + i);
}
cn.Close();
showdata();
clear();
}
}
}
public bool empid()
{
using (SqlConnection con = new SqlConnection("Data Source=SAFIYA-PC;Initial Catalog=dbEmployee;User ID=sa;Password=sa$123"))
{
con.Open();
string query = "select empcode from Employee where empcode = '" + txtempcode.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
empCode = dr["empcode"].ToString();
if (empCode != "0")
{
MessageBox.Show("Id already Existed Please use Another One!!!!!!");
return false;
}
con.Close();
}
return true;
}
}
Edit: the comment below is quite right, the immediate issue is that you have single quotes around the data you are trying to put in the contactno numeric(18, 0) field which is telling SQL to interpret that value as a varchar.
Change "','" + txtcont.Text + "','" to "'," + txtcont.Text + ",'" (i.e. remove the single quotes either side of the text box value) and do the same for any other numeric fields.
However, as is mentioned in other responses, this general approach of concatenating together a sql command string is not recommended from a security point of view. The preferred option is to use a parametrised query.
Using a parametrised query will also make it easier to deal with any nullable fields, as per this example.
(Edited to correct the answer in response to comment from Steffen)
Why don't you use parameters? It prevents your code from SQL Injection and you don't have to convert values and code is much more readable. Look at sample (it is for select statement but the same works for insert/update/delete statement):
var connectionString = "some connection string";
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection)) {
command.Parameters.Add(new SqlParameter("Name", dogName));
var reader = command.ExecuteReader();
while (reader.Read()) {
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight,
name,
breed);
}
}
}
You are directly storing the text value of your controls in your numeric fields (contactno, pf_acc_no and basic_sal). Are the values really sql-string representations of numeric values?
I would try to convert them to numeric value
double dValue = 0.0;
double.TryParse(textBox1.Text, out dValue);
and then, in the sql string convert to their sql-string representations with dValue.ToString() or a special dedicated method.
As per your table structure, there are 3 fields that are of numeric datatype. These are - contactno, pf_acc_no and basic_sal
And the values for these fileds are txtcont.Text, txtqibacc.Text and txtnetsalary.Text respectively, And your are also putting ' around them, that is why they are being treated as varchar filed.
While constructing the sql statement, you should pass the values for these fields as numeric, which is to say without ' marks. So just remove ' before and after these fields and your query should work fine.
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "'," + txtcont.Text + ",'" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', " +
txtqibacc.Text + ", '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "'," + txtnetsalary.Text + ",'" + txtremark.Text + "',#empimage) ", cn);
In case you need to pass null to these numeric fields, use DBNull.Value as shown here -
Assign Null value to the Integer Column in the DataTable
Constructing queries like these are prone to SqlInjection, suggest to use parameterized queries instead.
Actually, your code is very vulnerable to SQL-injection attacks. But I don't changing your programming style; I'm changing just your insertion query:
SqlCommand cmd = new SqlCommand(#"
INSERT INTO Employee
(empcode, firstname, lastname, gender, address, contactno,
bloodgroup, dateofbirth, country, qid, passportno, passportexpiredate,
designation, doj, doexpid, pf_acc_no, agreementstartdate, agreementenddate,
department, basic_sal, remarks, empimage)
VALUES
('" + txtempcode.Text + "',
'" + txtfrstname.Text + "',
'" + txtlstname.Text + "',
'" + combogender.Text + "',
'" + txtaddr.Text + "',
" + txtcont.Text + ",
'" + txtblodgrp.Text + "',
'" + dob.Value.ToString("yyyy/MM/dd") + "' ,
'" + txtcountry.Text + "',
'" + tqid.Text + "',
" + txtpassportno.Text + ",
'" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combodesig.Text + "',
'" + doj.Value.ToString("yyyy/MM/dd") + "',
'" + doexpqid.Value.ToString("yyyy/MM/dd") + "',
'" + txtqibacc.Text + "',
'" + agreestartdate.Value.ToString("yyyy/MM/dd") + "',
'" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combobranch.Text + "',
" + txtnetsalary.Text + ",
'" + txtremark.Text + "',
#empimage) ", cn);

How to save a picture to an access database table?

I am using this code to save a picture into an access database table:
byte[] fromPath = File.ReadAllBytes(Picture_Path);
byte[] fromPath2 = File.ReadAllBytes(BacksidePicture_Path);
con.Open();
string query = "Insert Into DML_Books_List (" +
"ID,ISNBORCode, Title, Donor, DocType, Edition, Author1, Author2, Author3, " +
"Author4, Translator, Publisher, Subject, USubject, Shelf, Cost, " +
"Language, Pages, Image, BImage, Description, Date) VALUES ('" +
"2" + "','" + ISNB_AddBook_Books_TXT.Text + "', '" +
Title_AddBook_Books_TXT.Text +
"', '" + Donor_AddBook_Books_TXT.Text + "', '" +
DocType_AddBook_Books_CBE.SelectedItem + "', '" +
Edition_AddBook_Books_TXT.Text + "', '" +
Author1_AddBook_Books_TXT.Text + "', '" +
Author2_AddBook_Books_TXT.Text + "', '" +
Author3_AddBook_Books_TXT.Text + "', '" +
Author4_AddBook_Books_TXT.Text + "', '" +
Translator_AddBook_Books_TXT.Text + "', '" +
Publisher_AddBook_Books_CBE.SelectedItem + "', '" +
Subject_AddBook_Books_CBE.SelectedItem + "', '" +
USubject_AddBook_Books_CBE.SelectedItem + "', '" +
Shelf_AddBook_Books_CBE.SelectedItem + "', '" +
Cost_AddBook_Books_TXT.Text + "', '" +
Language_AddBook_Books_CBE.SelectedItem + "', '" +
Pages_AddBook_Books_TXT.Text + "', '" +
#fromPath + "', '" + #fromPath2 + "', '" +
Description_AddBook_Books_MemoEdit.Text + "', '" +
Date_AddBook_Books_TXT.Text + "')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
con.Close();
But it has some problems.
Please Help Me solve this problem.
Thank you
OleDb.OleDbConnection cn = new OleDb.OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "\\data.mdb";
cn.Open();
byte[] arrImage = null;
string strImage = null;
IO.MemoryStream myMs = new IO.MemoryStream();
//
if ((this.picPhoto.Image != null)) {
this.picPhoto.Image.Save(myMs, this.picPhoto.Image.RawFormat);
arrImage = myMs.GetBuffer;
strImage = "?";
} else {
arrImage = null;
strImage = "NULL";
}
OleDb.OleDbCommand myCmd = new OleDb.OleDbCommand();
myCmd.Connection = cn;
myCmd.CommandText = "INSERT INTO tblstudent(stdid, [name], photo) " + " VALUES(" + this.txtID.Text + ",'" + this.txtName.Text + "'," + strImage + ")";
if (strImage == "?") {
myCmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage;
}
Interaction.MsgBox("Data save successfully!");
myCmd.ExecuteNonQuery();
cn.Close();
Source
use parameters like below code:
Assume you have two columns in your table called ID and Image. Now you going to insert data using SQL parameters
you need SQL statement like
Insert Into DML_Books_List(ID, [Image]) values (#id, #image)
#id and #image are the given names for parameters. You can set the parameter values by parameter name.
var pic = File.ReadAllBytes(yourFileName);
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("Insert Into DML_Books_List(ID, [Image]) values (#id, #image)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", pic);
cmd.ExecuteNonQuery();
}
Use parametrized query..
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database");
OleDbCommand command = connection.CreateCommand();
imageData = ReadByteArrayFromFile(#"c:\test.jpg");
command.CommandText = "Insert into SomeTable (Name, ImageData) VALUES (#Name, #Img)"
command.Parameters.AddWithValue("#Name", "theName");
command.Parameters.AddWithValue("#Img", imageData);
command.ExecuteNonQuery();

Updating Database

So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();
You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";
Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.
Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.
In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.

Categories

Resources