I am trying to insert data into a table in MS Access. I keep getting the error Missing semicolon (;) at end of SQL statement. or a different error saying that i my Insert query needs to have a value or table in it. Here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace MiddleWare
{
public partial class Sales : Form
{
public Sales()
{
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int empId = int.Parse(txtEmpID.Text);
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper)
SELECT #EmpID FROM (Emplopyee)";
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#Printers", OleDbType.VarWChar).Value = txtPrinters.Text;
cmd.Parameters.AddWithValue("#Ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.AddWithValue("#Paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.AddWithValue("#EmpID", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text);
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}
private void Sales_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DataSet1.DataTable1' table. You can move, or remove it, as needed.
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
}
private void btnReport_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb");
{
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
this.reportViewer1.RefreshReport();
}
}
}
}
You should seperate the queries by semicolon
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper);
SELECT #EmpID FROM (Emplopyee)";
Also you can't pass the column name as parameter. In that case use dynamic query.
you should change the query to this:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers,#Ink,#Paper,
SELECT EmpID FROM (Employee) )";
It most likely should read:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers, #Ink, #Paper, #EmpID)";
The "cmd.Paramter.AddWithValue" are unnecessary.
Try formatting your cmdText as
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper])
VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ")
This clears up confusion of "cmd.Paramter.AddWithValue" duplicating or overriding values.
Rewritten btnUpdate_Click (also not sure if Emplopyee is a typo or not)
private void btnUpdate_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper]) VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ") SELECT " + textEmpID.Text + " FROM (Emplopyee)";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}
Related
I've created a simple Windows form to input data into a SQL Server database table. On the surface, it seems fine, no errors, but after submitting data into table, that data doesn't appear. I've looked at the where the connection is pointing and that seems fine. so I'm stuck at the moment. Any help would be great.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp7
{
public partial class Onbutton1_Click : Form
{
public Onbutton1_Click()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
String str =
"den1.mssql7.gear.host;database=generic;UID=generic;password=Generic";
String cmdText1 = "INSERT INTO TEST1 (Name) VALUES ('%'+ #Name + '%')";
String cmdText2 = "INSERT INTO TEST1 (Age) VALUES ('%'+ #Age + '%')";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd1 = new SqlCommand(cmdText1, con);
SqlCommand cmd2 = new SqlCommand(cmdText2, con);
cmd1.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = textBox1.Text;
cmd2.Parameters.Add("#Age", SqlDbType.VarChar, 255).Value = textBox2.Text;
con.Open();
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
DataSet ds = new DataSet();
con.Close();
}
catch (Exception es)
{
MessageBox.Show("Complete");
}
}
}
Your problem lies here
String cmdText1 = "INSERT INTO TEST1 (Name) VALUES ('%'+ #Name + '%')";
String cmdText2 = "INSERT INTO TEST1 (Age) VALUES ('%'+ #Age + '%')";
This needs to be
String cmdText1 = "INSERT INTO TEST1 (Name) VALUES (#Name)";
String cmdText2 = "INSERT INTO TEST1 (Age) VALUES (#Age)";
Btw, curious why this is two separate statements. If you want to insert Name and Age to a single row, it needs to be a single query.
String cmdText = "INSERT INTO TEST1 (Name,Age) VALUES (#Name,#Age)";
cmd1.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = textBox1.Text;
cmd1.Parameters.Add("#Age", SqlDbType.VarChar, 255).Value = textBox2.Text;
Thanks #Crowcoder for the prompt the exception indicated a keyword error. Just wanted a little more than I had given it.
String str ="server=den1.mssql7.gear.host;
database=generic;
UID=generic;
password=Generic";
I know this title seems to be repeated a lot but I tried to search and didn't find the answer.
Code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {}
protected void gv_master_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = gv_master.SelectedRow;
// Display the first name from the selected row.
// In this example, the third column (index 2) contains
// the first name.
lbl_reqNoV.Text = row.Cells[1].Text;
lbl_reqNoV.Visible = true;
lbl_reqNo.Visible = true;
SqlConnection sqlConnection1 = new SqlConnection("Data Source=saitest01;Initial Catalog=SAI_website;Persist Security Info=True;User ID=sa;Password=sai#987");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader DR1;
DR1 = cmd.ExecuteReader();
DR1.Read();
// Data is accessible through the DataDR1 object here
gv_full.DataSource = DR1;
gv_full.DataBind();
}
}
the problem is you where adding the name of Connection in the query text which is ofcource not recognized by sqlserver the correct format was
var cmd = new SqlCommand("Select * from purchase Where ReqNo = #reqno",sqlConnection1)
or you can do this
cmd.CommandText = "Select * from purchase Where ReqNo = #reqno";
cmd.Parameters.AddWithValue("reqno",lbl_reqNoV.Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
you should always use parameters in query to avoid Sql Injection
just change following
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
with,
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "' ";
Above will make your code working. But you should modify you code to handle SQL Injection. As answered by #Usman
I am working with a simple program and now I got stuck with a problam that is encrypting and decrypting the password and storing them in the database. The logic I am working with is encrypting the password but it is not storing in the database, instead it is throwing an error showing below
System.Data.SqlClient.SqlException: Incorrect syntax near '='.
My Code
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;
using System.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm6 : System.Web.UI.Page
{
SqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con1.Open();
SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=#USERNAME and PASSWORD=#PASSWORD ", con1);
cmd1.Parameters.AddWithValue("#username", txtUserName.Text);
cmd1.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('userName is already availables')</script>");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con.Open();
string strQuery = EncodePasswordToBase64("insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text + "','" + txtPassword.Text + "')");
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(strQuery, connection);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("login.aspx");
}
con1.Close();
}
public static string EncodePasswordToBase64(string password)
{
try
{
byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
}
}
Question is: What I am doing wrong here?
You are encoding the complete query instead you should only encode the password
string strQuery = EncodePasswordToBase64("insert ....
It should be:
string strQuery = "insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text +
"','" + EncodePasswordToBase64(txtPassword.Text) + "')");
You should use SqlParameter and make a Parameterized query instead o string concatenation
string strQuery = "insert into admin( USERNAME,PASSWORD) values(#pUserName, #pPassword)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#pUserName", txtUserName.Text");
cmd.Parameters.AddWithValue("#pPassword", EncodePasswordToBase64(txtPassword.Text))
I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
how are you,sir my code is correct means there is no error after debugging that code.My goal is that if the user click on button(which is placed in default.aspx,for example)then the database table is created in database(database placed within sql express),I write the code for that purpose we debug the code and there is no error in the code .when i click the button(in runtime).when i check the database(which is in the sql express)there is no table is created in that database.please sir solve my problem.The code written in c# behind the button is that:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//using PractiseWeb.DataSet1TableAdapters;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
using System.Data.Odbc;
using ADOX;
using ADODB;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
conn = new SqlConnection(connectionString);
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
THANKS SIR
Remove the try-catch and see what's happening. Writing to the console isn't going to help much in an ASP.NET app. :)
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (conn = new SqlConnection(connectionString))
{
if (!(conn.State == ConnectionState.Open))
{
conn.Open();
}
string sql = "CREATE TABLE mySchoolRecord(StudentId INTEGER CONSTRAINT PkeyMyId PRIMARY KEY, Name CHAR(50)," + "Address CHAR(255)," + "Contact INTEGER));";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (1, 'Mr. Manish', " + " 'Sector-12,Noida', 2447658 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (2, 'Mr. Ravi', " + " 'New Delhi', 2584076521 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "INSERT INTO mySchoolRecord (StudentId, Name,Address,Contact) VALUES (3, 'Mr. Peter', " + " 'United States', 25684124 );";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
#sayyer ,
follow the below steps
1)can you copy your sql and paste on sqlserver directly and see if it creating or not?? do a break on exception while debuggin ,it will tell you if there are any exceptions in the code
2) Check your database connection
3) check all the formating for the insert statements.
Best way to fix the issue is do ctr + alt + E and check break on exceptions, that will fix your problem
Try removing semicolons from SQL queries.