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!
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 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 ' '.
This question already has an answer here:
Column name or number of supplied values does not match table definition - Unable to identify the root cause
(1 answer)
Closed 5 years ago.
I keep getting a this error: System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__3214EC0750F0A8B2'. Cannot insert duplicate key in object 'dbo.Table'. The duplicate key value is ().
The statement has been terminated.'
I don't know what I did wrong, anyone have a clue?
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 FBLA_Project_1
{
public partial class Form2 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\LUCY\Documents\testerfile.mdf;Integrated Security=True;Connect Timeout=30");
public Form2()
{
InitializeComponent();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void Form2_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText= "insert into [Table] (Id, Name, EmployeeID, Sunday) values('" + textBox2.Text+"','"+textBox4.Text+"','"+textBox1.Text+"','"+textBox3.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Data has been put in succefully ");
}
public void disp_data()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from table ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
}
Line 33 is around where I get my error. It's really annoying after tinkering around for hours and being in the same place.
In your insertquery the number of the values provided (4) don't match the number of the columns defined during table creation
then you should explicitally assign the column name (eg: assuming you columns name are col1, col2, col3, col4)
cmd.CommandText="insert into [Table] (col1, col2, col3, col4)
values('"+textBox2.Text+"','"+textBox4.Text+"','"+textBox1.Text+"','"+textBox3.Text+"')";
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
In Login.aspx.cs file
The codes are following
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;
using System.Web.Configuration;
namespace Leave_Management
{
public partial class Login : System.Web.UI.Page
{
//private string strcon = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(#"Data Source=TAUFIQ-PC\SQLEXPRESS;Initial Catalog=LM;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string checkuser = "select UserName from [User] where UserName='" + TextBoxUN + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
string checkpass = "select password from [User] where UserName='" + TextBoxUN + "'";
SqlCommand passcom = new SqlCommand(checkpass, conn);
string password = passcom.ExecuteScalar().ToString().Replace(" ", "");
conn.Close();
if (password == TextBoxPass.Text)
{
Response.Redirect("Registration.aspx");
}
}
}
}
}
An Error is showing as
"NullReferenceException was unhandled by user code"
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
Please help me to solve this.
You can just simplify your code by checking both username and password from the SQL statement:
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string SQL = "select UserID from [User] where UserName=#UserName AND Password=#Password";
SqlCommand com = new SqlCommand(SQL, conn);
com.Parameters.AddWithValue("#UserName", TextBoxUN.Text);
com.Parameters.AddWithValue("#Password", TextBoxPass.Text);
SqlDataReader data = com.ExecuteReader();
if (data.HasRows) // username and password match
{
conn.Close();
Response.Redirect("Registration.aspx");
}
else
{
conn.Close();
// display error here
}
}
I assume that UserID is the primary key of your Users table. You can use other column names if you want.
I also used parameters to avoid SQL injection. Cheers!
Too long for a comment, there are many things wrong with your code:
You are concatenating user-specified values into SQL queries. Don't do it, use parameters.
You are putting TextBoxUN into the SQL, you probably want TextBoxUN.Text. This is the reason you get null, since there is no user with that name.
You must take the value provided by ExecuteScalar() and check if it is null. Now it is, so you get a clear error about it.
Why get the username from the database with the username and then check for password? You can check for password and username with one query.
Do not store passwords in cleartext in the database! Use hash functions.
if temp comes up as null, then you will get the error. I would try:
...
int temp = 0;
try {
temp = Convert.ToInt32(com.ExecuteScalar().ToString());
} catch (exception) {}
...