I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.
when I run the program; it said the error near to table!
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 WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string SOURCE = #"Data Source=DESKTOP-K39PU4T\SQLEXPRESS;Initial Catalog=Mohamed;Integrated Security=True";
SqlConnection CON = new SqlConnection(SOURCE);
CON.Open();
MessageBox.Show("DB Connected");
string SqlSelectQuery = " Select*From Table Where ID ="+ int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Surname"].ToString());
textBox4.Text = (dr["Lastname"].ToString());
}
else
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
MessageBox.Show("No Record Found Please Enter Correct Id");
}
CON.Close();
}
}
}
I want to load the data from SQL Server to ASP.NET in Visual Studio
Table is key word, if you have table named "Table" you may need to use [Table] for escape keyword in the SQL string, otherwise give the correct table name instead of Table. also you better use parameters instead of concatenating string as sql statement.
string SqlSelectQuery = "Select * From [Table] Where ID =#ID";
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
cmd.Parameters.AddWithValue("#ID", int.Parse(textBox1.Text));
What is the table name from which you want to get data?
if its name is Table then replace " Select*From Table Where ID =" with " Select * From \"Table\" Where ID ="
otherwise replace Table with actual table name
Related
I am designing a planner and I'm having in issue when I click on my add task button. Once I click on it, my program crashes and this error is displayed:
"System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'table'.'"
Where would I find the incorrect syntax?
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 InfoHub
{
public partial class Planner : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\epoch\source\repos\InfoHub\InfoHub\planner.mdf;Integrated Security=True;Connect Timeout=30");
public Planner()
{
InitializeComponent();
}
private void Planner_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void addTask_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
}
You are using sql insert command incorrectly:
cmd.CommandText = "insert into table values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
table is sql keyword and it is not treated as table name. Try adding writing it as 'table' to inform sql that 'table' is name of particular table and not keyword:
cmd.CommandText = "insert into 'table' values('" + textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"')";
generally it is good practice to always write names in ' '.
I want to change a user's name. The current name and the new one are textbox inputs. On debugging, I get the exception that f.e. "JOHN" is not valid in this context. Why does this happen? It should expect a string and receives it. Where is the mistake?
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
namespace WebApplication1
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "...";
OleDbCommand changeFirstName = new OleDbCommand("UPDATE Usertable SET Name =" + #NewFN + " WHERE Name = " + #FN + "", con);
changeFirstName.Parameters.Add("#NewFN", OleDbType.VarChar).Value = getNewFirstName.Text;
changeFirstName.Parameters.Add("#FN", OleDbType.VarChar).Value = getFirstName.Text;
con.Open();
try
{
int i = changeFirstName.ExecuteNonQuery();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
con.Close();
}
}
}
The parameter tokens are part of the SQL and live inside it:
OleDbCommand changeFirstName = new OleDbCommand(
"UPDATE Usertable SET Name = #NewFN WHERE Name = #FN", con);
Side notes:
the connection and command are both IDisposable and should use using
when possible, prefer the provider-specific provider over OleDB - for example, if you're connecting to SQL-Server, use SqlConnection / SqlCommand
you may find tools like "Dapper" save you a lot of work here
Example of all 3 combined:
using(var con = new SqlConnection("..."))
{
con.Execute("UPDATE Usertable SET Name = #NewFN WHERE Name = #FN",
new {
NewFN = getNewFirstName.Text,
FN = getFirstName.Text,
});
}
I got it now. Because it is OleDb I can not use # in the Command string. Instead of #NewFN and #FN I have to use ?. On Parameter.Add I have to use #Name to give them a value. Here is an example:
OleDbCommand changeFirstName = new OleDbCommand (”UPDATE Usertable SET Name = ? WHERE Name = ?“);
changeFirstName.Parameters.Add(”#Name“, OleDbType.VarChar).Value = getNewFirstName.Text;
Hello everyone this is the code i wrote in order to get the data from a simple form and import it into my DataBase:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=ICSD-DB\\ICSDMSSQLSRV;Initial Catalog=icsd15005;Integrated Security=True");
//1os tropos
String sqlString = "INSERT INTO pr_foititis VALUES(#arithmos_taut,#onoma,#eponymo, #imerominia_proslipsis,#imerominia_gennisis,#misthos)";
//2os tropos mh asfales, Sql injection, gia na to ektelesoume afairoume apo kato tis entoles pou ksekinoun me command.Parameters.Add
//String sqlString = "INSERT INTO pr_foititis VALUES('"+id_Tb.Text+"','"+name_Tb.Text;+"','"+surname_Tb.Text;+"', "+age_Tb.Text;+")";
try
{
connection.Open();
SqlCommand command = new SqlCommand(sqlString, connection);
command.Parameters.Add("#arithmos_taut", SqlDbType.Int).Value = TextBox1.Text;
command.Parameters.Add("#onoma", SqlDbType.VarChar).Value = TextBox2.Text;
command.Parameters.Add("#eponymo", SqlDbType.VarChar).Value = TextBox3.Text;
command.Parameters.Add("#imerominia_proslipsis", SqlDbType.Date).Value = TextBox4.Text;
command.Parameters.Add("#imerominia_gennisis", SqlDbType.Date).Value = TextBox5.Text;
command.Parameters.Add("#misthos", SqlDbType.Float).Value = TextBox6.Text;
command.ExecuteNonQuery();
connection.Close();
resultLabel.Text = "All Good!";
}
catch (Exception ex)
{
resultLabel.Text = ex.ToString();
}
}
}
Here is the Exception:
System.Data.SqlClient.SqlException (0x80131904): Column name or number of supplied values does not match table definition. (line 35)
Unless the number (and order) of the VALUES you have in your INSERT statement match the number and order of columns in your table exactly, you need to define the columns.
String sqlString = "INSERT INTO pr_foititis (ColumnA, ColumnB, ColumnC, ColumnD, ColumnE, ColumnF) VALUES (...)"
You are getting this error because your table contents more columns than your supplied values.
Just cross check your table columns or use below code.
String sqlQuery = "INSERT INTO pr_foititis (Column1, Column2, Column3, Column4) VALUES (Value1,Value2,Value3,Value4)"
Hope this will help you.
Thanks!
I get this error "ora-00928 missing select keyword" when using a button to submit the query. I have other queries on other buttons and the select statements work but for some reason the insert statement doesnt work.
I've seen other posts on this error but nothing seems to help mine
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;
namespace Oracle
{
public partial class Register : Form
{
string name;
int pass;
int repass;
string email;
public Register()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=MSDAORA;Data Source=DESKTOP-HQCK6F1:1521/CTECH;Persist Security Info=True;User ID=system;Password=G4ming404;Unicode=True");
OleDbCommand cmd = new OleDbCommand();
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
cmd.Connection = con;
cmd.CommandText = "INSERT INTO SYSTEM.CUSTOMER('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')" + "VALUES('%"+ null + "%','%'" + txtname.Text + "%','%'" + txtemail.Text + "%','%'" + txtpass.Text + "%')";
con.Open();
if (pass == repass)
{
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else {
MessageBox.Show("Success!");
}
MessageBox.Show("User has been created");
this.Close();
Form1 login = new Form1();
login.Show();
}
else {
MessageBox.Show("Password mismatch");
}
con.Dispose();
}
There are some problems in your query.
First you don't need single quotes around the column names, You need double quotes only if any of your columns has the same name as a reserved keyword.
Second problem is the string concatenation of the input boxes text to the query command. This should be avoided at all cost because it is the source of parsing problems and sql injection hacks. Use parameters instead.
Finally your OleDbConnection should be local to your method and inside a using statement to ensure correct disposing of the unmanaged resources also in case of exceptions
private void button1_Click(object sender, EventArgs e)
{
name = txtname.Text;
pass = Convert.ToInt32(txtpass.Text);
repass = Convert.ToInt32(txtrepass.Text);
email = txtemail.Text;
if (pass != repass)
{
MessageBox.Show("Password mismatch");
return;
}
string cmdText = #"INSERT INTO SYSTEM.CUSTOMER
(CUSTOMER_NAME, CUSTOMER_EMAIL, CUSTOMER_PASSWORD)
VALUES(?,?,?)";
using(OleDbConnection con = new OleDbConnection(.......))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("p1", OleDbType.VarChar).Value = txtname.Text;
cmd.Parameters.Add("p2", OleDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("p3", OleDbType.VarChar).Value = txtpass.Text ;
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
{
MessageBox.Show("Record not inserted");
}
else
{
MessageBox.Show("Success!");
MessageBox.Show("User has been created");
}
}
Form1 login = new Form1();
login.Show();
}
I have also removed the passing of a parameter for the CUSTOMER_ID field. This seems to be a field that is calculated automatically by Oracle (a Sequence?) and thus you don't need to provide a value for it.
Finally an advice. Do not store password in plain text in the database. This is a security risk very seriours. You should read Best way to store passwords in a database
Your CommandText seems wrong. Why do you wrap all values with '%'? And you should pass null as string. Concatination with null does not changes any string value.
I think it should be:
cmd.CommandText = $#"INSERT INTO SYSTEM.CUSTOMER
('CUSTOMER_ID', 'CUSTOMER_NAME', 'CUSTOMER_EMAIL', 'CUSTOMER_PASSWORD')
VALUES(NULL, {txtname.Text}, {txtemail.Text}, {txtpass.Text})";
I am currently building an application in C#. In this application, people give values in a label and that values will be saved in a database. This also works at the moment. What I want is the following:
The people can see their own values back in a datagridview. If I do this with the wizard of the datagridview I can't select label2.Text(this is the customerID).
The query I used below is the following:
SELECT * FROM prestaties WHERE gebruikerid = '" + label1.Text + "'";
But it doesn't work. I don't see anything in my datagrid.
Sorry for my bad English. I hope you can understand me.
The code below I already have, but it doesn't work
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Eindopdracht
{
public partial class resultaten : Form
{
public resultaten()
{
InitializeComponent();
dataGridView1.Show();
}
private string username;
public void displaydata(String ddata)
{
OleDbConnection conn = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string select = "SELECT * FROM prestaties WHERE gebruikerid = '" + label2.Text + "'";
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(select, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.DataSource = ds.tables[0];
conn.Close();
}
public void setUsername(String name)
{
username = name;
label1.Text = username;
setID();
}
public void setID()
{
OleDbConnection vcon = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string selectie = "SELECT id FROM inlog WHERE Username='" + label1.Text + "'";
OleDbCommand vcom1 = new OleDbCommand(selectie, vcon);
vcon.Open();
vcom1.ExecuteNonQuery();
OleDbDataReader dr = null;
dr = vcom1.ExecuteReader();
while (dr.Read())
{
var waarde = dr.GetValue(0);
label2.Text = waarde.ToString();
}
I don't know if my code is 100% correct. I've build this by myself. If I use the class displayData in the begin next to InitializeComponent(); I will get an error.