SQL ASP.NET INSERT troubles (part 2) - asp.net

And i am back again.
I have asked a similair question before, but even with the help of the previous anwser and trying it with questionmarks or instead of Add i've tried AddWithValue i didn't have any luck.
I tried to change the txt_Naam to txt_Naam.Text, nothing.
Also putting [] around the columnnames, no luck.
It keeps giving me this "Syntax error in INSERT INTO statement.".
This time i got nowhere with the code below.
Probably something small, but i can't figure it out. (Again...)
protected void btn_final_Click(object sender, EventArgs e)
{
string fact_adres = txt_Naam.Text + "," + txt_Anaam.Text + "," + txt_Adres.Text + "," + txt_Toevoeg.Text + "," + txt_Pcode.Text + "," + txt_Plaats.Text + "," + txt_Email.Text ;
string fact_adres1 = txt_Naam1.Text + "," + txt_Anaam1.Text + "," + txt_Adres1.Text + "," + txt_Toevoeg1.Text + "," + txt_Pcode1.Text + "," + txt_Plaats1.Text + "," + txt_Email1.Text;
string a = "1";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; "
+ "Data Source=|DataDirectory|webwinkel.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (?, ?, ?);";
cmd.Parameters.Add("#factuur_adres", OleDbType.VarChar, 125).Value = fact_adres;
cmd.Parameters.Add("#verzend_adres", OleDbType.VarChar, 125).Value = fact_adres1;
cmd.Parameters.Add("#totaal_prijs", OleDbType.VarChar, 7).Value = a;
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
reader.Close();
}
catch (Exception exc)
{
Label1.Text = exc.Message;
}
finally
{
conn.Close();
Session["Winkelwagen"] = null;
}
}

You command text should be
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (#factuur_adres,#verzend_adres, #totaal_prijs)";
Updated answer:
run your code with setting parameters, directly pass the value and check that it works or not
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES ('abc','def','adf')";

When you are inserting don't you have to use
cmd.ExecuteNonQuery()
Instead of cmd.ExecuteReader() ??

Related

Incorrect syntax near keyword 'd1'

The SQL query works in SQL Server Management Studio. But, in Visual studio it gives an error
Incorrect syntax near D1
Code:
private void GetDataByID(string _id)
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sqlCommand = "SELECT d1.*, d2.* FROM KFM.dbo.ToolBoxDocContent as d1, KFM.dbo.ToolBoxDocument as d2" +
"where d1.DocumentId = d2.DocumentId and = d2.DocumentId =" + _id;
SqlCommand cmd = new SqlCommand(sqlCommand, connection);
SqlDataReader MyReader;
try
{
connection.Open();
MyReader = cmd.ExecuteReader();
while (MyReader.Read())
{
string sDueWeek = MyReader["DueWeek"].ToString();
string sTitle = MyReader["DocumentTitle"].ToString();
//string sEnglishBodyContent = MyReader["DocumentBody"].ToString();
//string sFrenchBodyContent = MyReader["DocumentBody"].ToString();
txb_Week.Text = sDueWeek;
txb_Title.Text = sTitle;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Change the query as shown below
"SELECT d1.*, d2.* FROM KFM.dbo.ToolBoxDocContent as d1, KFM.dbo.ToolBoxDocument as d2
where d1.DocumentId = d2.DocumentId and d2.DocumentId ='" + _id + "'";
In your query, you also have entered = sign after and.
Try this code
string sqlCommand = "SELECT d1.*, d2.* FROM KFM.dbo.ToolBoxDocContent d1 inner join KFM.dbo.ToolBoxDocument as d2 on d1.DocumentId = d2.DocumentId " + " where d2.DocumentId = " + _id;
Also it's better to write store procedure instead and call from your c# code.
private void GetDataByID(string _id)
{
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
string sqlCommand = "SELECT d1.*, d2.* "
+ " FROM KFM.dbo.ToolBoxDocContent as d1"
+ " INNER JOIN KFM.dbo.ToolBoxDocument as d2 ON d1.DocumentId = d2.DocumentId"
+ " WHERE d2.DocumentId = #ID";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(sqlCommand, connection))
{
cmd.Parameter.Add("#ID", SqlDbType.Int).Value = int.Parse(_id);
try
{
connection.Open();
using (SqlDataReader MyReader = cmd.ExecuteReader()_
{
while (MyReader.Read())
{
string sDueWeek = MyReader["DueWeek"].ToString();
string sTitle = MyReader["DocumentTitle"].ToString();
//string sEnglishBodyContent = MyReader["DocumentBody"].ToString();
//string sFrenchBodyContent = MyReader["DocumentBody"].ToString();
txb_Week.Text = sDueWeek;
txb_Title.Text = sTitle;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
One thing I have noticed in your query is that
space is not provided properly before two joins using '+'. Use space before where
incorrect syntax at where clause. remove extra '=' after and at and = d2.DocumentId = " + _id
Your final query will look like as mentioned below:
string sqlCommand = "SELECT d1.*, d2.* FROM KFM.dbo.ToolBoxDocContent as d1, KFM.dbo.ToolBoxDocument as d2" +
" where d1.DocumentId = d2.DocumentId and d2.DocumentId =" + _id;
Update:
string sqlCommand = "SELECT d1.*, d2.* FROM KFM.dbo.ToolBoxDocContent as d1, KFM.dbo.ToolBoxDocument as d2" +
" where d1.DocumentId = d2.DocumentId and d2.DocumentId = '" + _id + "'";

Error "External table is not in the expected format"

here is my code
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
string path = #"C:\Users\Mazen\Desktop\Source\Book1.xlsx";
String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + path + "; "
+ "Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
System.Data.DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT ID, Name From [" + SheetName + "]";
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter();
da.SelectCommand = cmdExcel;
da.Fill(ds);
}
its give an error how to fix it.. If i changed Jet to ACE so its gives an error
provider is not registered on the local machine. please help me
Try the following for your strExcelConn:
String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

The Microsoft Jet database engine cannot open the file

I am writing a code to query .CSV file using SQL below is my code which works perfectly fine
string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ fileDirectory + ";Extended Properties='text;HDR=YES;'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+"Order by 1 Desc";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
con.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, con);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, con);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, con);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
con.Close();
But when I am trying to call the same code from the function by passing the file path which is retrieved from asp.net file upload control it does not work. Please see the code below.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fupPath.HasFile)
{
string filename = Path.GetFileName(fupPath.FileName);
String csv_file_path = Path.Combine(Server.MapPath("~/Csv"), filename);
fupPath.SaveAs(csv_file_path);
Summery(csv_file_path);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
//dtSummary(csvData);
}
}
protected void Summery(string fileName)
{
//string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string fileDirectory = fileName;
//string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
// + System.IO.Path.GetDirectoryName(fileDirectory) + ";Extended Properties='text;HDR=YES;FMT=Delimited\'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+ "Order by 1 Desc";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
//OleDbConnection conn = new OleDbConnection(strCSVConnString);
conn.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, conn);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
daCust.Dispose();
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, conn);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
daProd.Dispose();
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, conn);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
daOrders.Dispose();
conn.Close();
}
You need to call a sheet name SheetName$ instead of file name SampleData.csv.
For example,
Select Count(order_id), order_id, contact_id from [SheetName$]
Normally, here is how you get a file path in ASP.Net, because you do not know the drive letter where your web application is hosted. In addition, you do not have access to a file located outside of web application.
var filePath = string.Format("{0}App_Data\\ExportImport\\{1}",
HttpRuntime.AppDomainAppPath, "SampleData.csv");

How can i write the following query as parametrized query?

I have been hearing about parametrized queries every time I ask a question about database here. It looks like I am not using parametrized queries and my code may suffer from SQL injection. So here is my code:
public void CreateStudent(int ID, String status, String email, String firstName, String lastName, String password, String level, String program)
{
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values ("
+ "'" + firstName + "'" + "," + "'" + lastName + "'" + ","
+ "'" + ID + "'" + "," + "'" + email + "'" + "," + "'" + level + "'" + "," + "'" + program + "'" + "," + "'" + status + "'"
+ "," + "'" + password + "'" + "," + "'" + "Student" + "'" + ")";
SqlCommand command = new SqlCommand(query1,con);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
Here is what I have tried:
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values(#firstName,#lastName,#ID,#email,#level,#program,#status,#password,Student)";
SqlCommand command = new SqlCommand(query1,con);
command.Parameters.AddWithValue("#firstName", firstName);
command.Parameters.AddWithValue("#lastName", lastName);
command.Parameters.AddWithValue("#ID", ID);
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue("#level", level);
command.Parameters.AddWithValue("#program", program);
command.Parameters.AddWithValue("#status", status);
command.Parameters.AddWithValue("#password", password);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
This gives an error saying that Student is an invalid column name. Actually, here I try to use "Student" as a string value to be added to the column Type. Can somebody write this query as a parametrized query so that I can understand it?
In that case it should be 'Student'
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values(#firstName,#lastName,#ID,#email,#level,#program,#status,#password,'Student')";
SqlCommand command = new SqlCommand(query1,con);
command.Parameters.AddWithValue("#firstName", firstName);
command.Parameters.AddWithValue("#lastName", lastName);
command.Parameters.AddWithValue("#ID", ID);
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue("#level", level);
command.Parameters.AddWithValue("#program", program);
command.Parameters.AddWithValue("#status", status);
command.Parameters.AddWithValue("#password", password);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
Check this link
public void CreateStudent(int ID, String status, String email, String firstName, String lastName, String password, String level, String program)
{
SqlConnection con = new SqlConnection(GetConnectionString());
using (
SqlCommand command =
new SqlCommand(
#"insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values
(#name, #surname, #id, #email, #level, #program, #status,#password,'Student')",
con))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("name", firstName));
command.Parameters.Add(new SqlParameter("surname", lastName));
command.Parameters.Add(new SqlParameter("id", ID));
command.Parameters.Add(new SqlParameter("email", email));
command.Parameters.Add(new SqlParameter("level", level));
command.Parameters.Add(new SqlParameter("program", program));
command.Parameters.Add(new SqlParameter("status", status));
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
}

i have this treeview for menu assignment. i want to know that can we find out if our rows have been updated. if yes then how?

the coding
foreach (TreeNode item in this.TreeView1.CheckedNodes)
{
if (item.Checked == true)
{
int strTreeValue = Convert.ToInt32(item.Value);
SqlCommand com = new SqlCommand("Update Role_Menu Set Role_id=('" + roleid + "')
Where Menu_id=('" + strTreeValue + "')", con);
com.ExecuteNonQuery();
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count == 0)
{
com = new SqlCommand("insert into Role_Menu(Role_id,Menu_id)
values('" + roleid + "','" + strTreeValue + "')", con);
com.ExecuteNonQuery();
}
}
in the above if(ds.tables.count == 0) i am trying to find if the rows have been updated or not but it is wrong and does not work. if a row is updated then how can we come to know it is updated and which one is updated.
You can use the code as follow
foreach (TreeNode item in this.TreeView1.CheckedNodes)
{
if (item.Checked == true)
{
int strTreeValue = Convert.ToInt32(item.Value);
SqlCommand com = new SqlCommand("Update Role_Menu Set Role_id=('" + roleid + "')
Where Menu_id=('" + strTreeValue + "')", con);
int i=com.ExecuteNonQuery();
if (i<= 0)
{
com = new SqlCommand("insert into Role_Menu(Role_id,Menu_id)
values('" + roleid + "','" + strTreeValue + "')", con);
com.ExecuteNonQuery();
}
}
Edit 1
You don't need to use SqlDataAdapter and DataSet
If you run the SQL from your question in a SqlCommand and check the return value of ExecuteNonQuery it should tell you how many records were affected.
From the documentation:
Return Value
Type: System.Int32
The number of rows affected.

Resources