Why is my Ajax data not sending through to my SQL Server - c#

I am trying to get my data from a web page to a server without requiring a page refresh. The js brings in the data; however, it (the data) does not reach my db, I am new to ajax and not sure if I am doing this correctly
JS:
function insert() {
let batchid = document.getElementById("batchID").value;
let batchname = document.getElementById("batchName").value;
let totenum = document.getElementById("toteNum").value;
let flower = document.getElementById("flowers").value;
let trim = document.getElementById("trim").value;
let wastemat = document.getElementById("wasteMaterial").value;
let empint = document.getElementById("empInital").value;
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insert.cshtml?bid=" + batchid + "&bn" + batchname + "&tn" + totenum + "&fl" + flower + "&tr=" + trim + "&wm" + wastemat + "&ei" + empint , false);
xmlhttp.send(null);
alert(" Record inserted successfully");
}
C#:
SqlConnection con = new SqlConnection(Server);
string batchID, batchName, toteNum, flowers, trim, wasteMaterial, empInital;
public void OnGet()
{
batchID = Request.Query["bid"].ToString();
batchName = Request.Query["bn"].ToString();
toteNum = Request.Query["tn"].ToString();
flowers = Request.Query["fl"].ToString();
trim = Request.Query["tr"].ToString();
wasteMaterial = Request.Query["wm"].ToString();
empInital = Request.Query["ei"].ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO HarvestedCannabis VALUES ('" + batchID.ToString() + "', '" + batchName.ToString() + "', " +
"'" + toteNum.ToString() + "', '" + flowers.ToString() + "', " +
"'" + trim.ToString() + "', '" + wasteMaterial.ToString() + "', " +
"'" + empInital.ToString() + "')";
cmd.ExecuteNonQuery();
con.Close();
The data is not being added to my db and I am not sure what I'm missing

Related

Trying to read data from sql database and show on textboxes - Visual C# (syntax error)

edit: I'm aware of SQL Injection.
First of all, I know my coding methods are terrible but thats what I can for now, extremely beginner on c#.
I'm trying to read data from SQL server and show them on Textboxes.
User going to write (and choose from cmbbox) some data on;
cmbIl.Text, cmbIlce.Text, cmbMahalle.Text, txtAda.Text, txtPafta.Text
and press the button for search.
If that data correspond to the values in sql database (true), some other data will be taken and shown at
txtTapuKodu.Text, txtPafta.Text, txtTapuAlani.Text, txtNitelik.Text,
rtxtImarDurumu.Text
But the code below gives that error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
private void btnSorgula_Click(object sender, EventArgs e)
{
string source = #"Data Source=YAGIZ-PC;Initial Catalog=imar_sorgu;Integrated Security=True";
SqlConnection con = new SqlConnection(source);
con.Open();
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
/* string sqlSelectQuery2 = "SELECT * FROM tablo_arsa WHERE ilce ='" + cmbIlce.Text + "'";
string sqlSelectQuery3 = "SELECT * FROM tablo_arsa WHERE mahalle ='" + cmbMahalle.Text + "'";
string sqlSelectQuery4 = "SELECT * FROM tablo_arsa WHERE ada = " + txtAda.Text;
string sqlSelectQuery5 = "SELECT * FROM tablo_arsa WHERE parsel = " + txtParsel.Text; */
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTapuKodu.Text = (dr["tapu_kodu"].ToString());
txtPafta.Text = (dr["pafta"].ToString());
txtTapuAlani.Text = (dr["tapu_alani"].ToString());
txtNitelik.Text = (dr["nitelik"].ToString());
rtxtImarDurumu.Text = (dr["imar_durumu"].ToString());
MessageBox.Show("İstek başarıyla okundu.");
}
else
{
MessageBox.Show("Okuma başarısız.");
}
con.Close();
}
The problem is that your where clause contains commas between the predicates. use AND instead.
change:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "', ilce = '" + cmbIlce.Text + "', mahalle = '" + cmbMahalle.Text + "', ada = '" + txtAda.Text + "', parsel = '" + txtParsel.Text + "'";
to:
string sqlSelectQuery = "SELECT * FROM tablo_arsa WHERE il = '" + cmbIl.Text + "' AND ilce = '" + cmbIlce.Text + "' AND mahalle = '" + cmbMahalle.Text + "' AND ada = '" + txtAda.Text + "' AND parsel = '" + txtParsel.Text + "'";
However, PLEASE read about SQL INJECTION. It is a very bad security issue and this is a perfect example.

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);
.....
}

Data type mismatch in criteria expression in WPF Application

Please help me out in this error.
I am using access database in C# and developing WPF application. Here, I am writing updating query and i got the below error :-
"Data type mismatch in criteria expression".
Here, Retail and Cut_Off both are checkbox. I added it later.When I added checkbox later it gives me this error.
I stored checkbox value like below :-
cmentity.Retail = chkRetailIndividualBidder.IsChecked.Value.ToString();
cmentity.Cut_Off = chkCutOff.IsChecked.Value.ToString();
Below code wrote in Clientmasterrepository.cs file
public int UpdateForAllClientInfo(ClientMaster cmentity)
{
string strQuery = "UPDATE ClientMaster SET " +
"Applied_Quantity = '" + cmentity.Applied_Quantity + "', " +
"Amount = '" + cmentity.Amount + "', " +
"Cheque_in_Favour = '" + cmentity.Cheque_in_Favour + "', " +
"Retail_Individual_Bidder = '" + cmentity.Retail + "', " +
"Cut_Off = '" + cmentity.Cut_Off + "' " +
"WHERE IsDeleted = " + 0;
return oConnectionClass.ExecuteNonQuery(strQuery);
}
below code wrote in connection.cs file:-
public int ExecuteNonQuery(string strQuery)
{
OleDbConnection oleDbConnection = new OleDbConnection(strConnectionString);
OleDbCommand oleDbCommand = new OleDbCommand(strQuery, oleDbConnection);
oleDbCommand.CommandText = strQuery;
oleDbCommand.CommandType = CommandType.Text;
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbConnection.Close();
return 1;
}

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