C# insert data into database windows form app - c#

I need to build a application where people can make a reservation but before doing that they need to fill in some information. I get this error code at the moment when i try to save the data: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
This is my code:
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.Threading.Tasks;
using System.Windows.Forms;
namespace BonTemps
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var Form1 = new Form1();
Form1.Show();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bonTempsDBDataSet.Tafel' table. You can move, or remove it, as needed.
this.tafelTableAdapter.Fill(this.bonTempsDBDataSet.Tafel);
}
private void btnOpslaan_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = (#"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres), VALUES ('" + txtNaam.Text + "','" + txtAdres.Text + "','" + txtWoon.Text + "','" + txtTel.Text + "','" + txtMail.Text + "'");
com.ExecuteNonQuery();
sc.Close();
}
}
}

Remove the comma Before VALUES.
If that is not enough, you can debug and copy the generated string from Command Text and try running it directly in SQL Server Mangement Studio or similar

A typographical error remove the COMMA before the word VALUES.

You have to pass an open SqlConnection to your SqlCommand to make it work:
com.Connection = sc;
Also, consider using named parameters to pass data to your query to make your query more error-proof:
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = #"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres) VALUES (#naam, #adres, #woon, #tel, #mail)";
com.Parameters.AddWithValue("#naam", txtNaam.Text);
com.Parameters.AddWithValue("#adres", txtAdres.Text);
com.Parameters.AddWithValue("#woon", txtWoon.Text);
com.Parameters.AddWithValue("#tel", txtTel.Text);
com.Parameters.AddWithValue("#mail", txtMail.Text);
com.ExecuteNonQuery();
sc.Close();

using (var sc = new SqlConnection("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True"))
{
using (var com = new SqlCommand("sql cmd text", sc))
{
try
{
sc.Open();
com.ExecuteNonQuery();
}
catch
{
}
}
}

Related

C# System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'table'.'

I create a table named Table with members (first name, last name, address). The program is throwing the error "incorrect syntax near the keyword 'table'". The application is to insert the data into the table. The code is for the new button exception handler.
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 Week4
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Testing.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
private void btnNew_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into [Member] values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + txtAddress.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Member added successfully");
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
private void btnCancel_Click(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
}
}
}
You need to use parameters to avoid sql injection
string sql = "insert into Member(col1, col2, col3) values(#val1, #val2, #val3)";
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Testing.mdf;Integrated Security=True;Connect Timeout=30"))
{
connection.Open();
using (SqlCommand cmd= new SqlCommand(sql, connection))
{
md.Parameters.Add("#val1", SqlDbType.Varchar, 50).value = txtFirstName.Text;
cmd.Parameters.Add("#val2", SqlDbType.Varchar, 50).value = txtLastName.Text;
cmd.Parameters.Add("#val3", SqlDbType.Varchar, 50).value = txtAddress.Text;
cmd.ExecuteNonQuery();
}
MessageBox.Show("Member added successfully");
}
table is a reserved keyword in SQL including MSSQL.
See all reserved keywords: https://learn.microsoft.com/en-us/sql/odbc/reference/appendixes/reserved-keywords?view=sql-server-ver15
Below code could work, but I strongly recommend not to use reserved keyword for a table name. (related answer: https://stackoverflow.com/a/695626/361100 )
cmd.CommandText = ("insert into [table] values ('"+txtFirstName.Text+"', '"+txtLastName.Text+"', '"+txtAddress.Text+"'))");
The error is general because it is not able to understand the '[Member]' in your code. It seems suspicious in [Member]. Your table name is Table, but you cannot use it since it is a reserved keyword. Try writing this way.
private void btnNew_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Member("FirstName","LastName","Address") values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + txtAddress.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Member added successfully");
}
Note: The ("FirstName","LastName","Address") are your table fields. Make sure your Table matches the cases (upper and lower) with that of your database table.
Hope this helps.

asp.net registration page not working properly

I am creating a simple registration page and I get an error which I believe has to do with not being able to find the table I have created, yet I made it locally.
Here is the error I get:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'Table'.
Any help would be fantastic.
Below I have posted the code that I have down so far:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Net.Mail;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string checkuser = userchecker();
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = changehere(com);
conn.Close();
if (temp == 1)
{
Response.Write("User Already Exists");
}
}
}
private string userchecker()
{
return "select count(*) from Table where UserName='" + TextBoxUN.Text + "'";
}
private static int changehere(SqlCommand com)
{
return Convert.ToInt32(com.ExecuteScalar().ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid NEWguid = Guid.NewGuid();
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table (ID, UserName, Email, Password) values (#ID, #Uname , #email, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#ID", NEWguid.ToString());
com.Parameters.AddWithValue("#Uname", TextBoxUN.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Redirect("manager.aspx");
Response.Write("Registration successful");
conn.Close();
}
catch (Exception)
{
Response.Write("Error:");
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{
}
}
Try this:
private string userchecker()
{
return "select count(*) from [Table] where UserName='" + TextBoxUN.Text + "'";
}
See the [] around Table, this is because Table is a reserved word in all SQL variants and you should escape it
Change the name of the table, table is a reserved word in SQL

What is the correct syntax for establishing an SQL connection and creating SQL Commands with VS2012?

I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
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;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
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 Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Changing textBox's content by clicking calendarMonth

I'm trying to make an agenda facility for my winform project. I want to display database records on textBox for specific date when user chose date on monthCalendar control. Below you can see my db table design, my winform design and my code and exception message that i'm getting. How can i fix this?
*ps: no need to suggest on using parametrized queries. i can and i will change it eventually
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.SqlClient;
namespace EKS
{
public partial class Agenda : Form
{
public Agenda()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.BackColor = Color.FromArgb(100, 88, 55, 55);
}
private void button1_Click(object sender, EventArgs e)
{
try {
string myQuery = "insert into agenda (input_agenda, input_date) values ('"+textBox1.Text.ToString()+"', '"+ monthCalendar1.SelectionStart +"')";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = myQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("agenda updated");
}
catch (Exception x) {
MessageBox.Show(x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try {
string deleteQuery = "DELETE FROM agenda WHERE input_date = '" + monthCalendar1.SelectionStart +"'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = deleteQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("delete succeeded");
}
catch(Exception x){
MessageBox.Show(x.ToString());
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
GetAgendaDetails(e.Start.Date);
}
private void GetAgendaDetails(DateTime x){
string myQuery = "select input_agenda from agenda where input_date = '" + x.Date.ToString() + "'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
try {
myConn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
textBox1.Text = myReader.GetString(100);
}
myConn.Close();
}
catch(Exception z){
MessageBox.Show(z.ToString());
}
}
}
}
Use DateSelected event of MonthCalendar control, Which will be fired when user selects a date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
AganedaInformation info = GetAgendaDetails(e.Start.Date);
}
Add a private method to query the database based on the passed selected date
Private AganedaInformation GetAgendaDetails(DateTime selectedDate)
{
//Add logic to query the database with the selected date and return the information
}

problem getting my data from access 2003 db into c# (dbReader.GetString error)

[got a bit further so its updated]
Hello There, i really hope you are able to help me!
Now the first part of my code does work, and I do get my report numbers out in my combobox, and i'm able to write that number to a lbl. now I need to take that number and get the rest of my data from my Access 2003 database, and drop them in a string (my output). ( I dont really want all the data loaded into my mem when i open the program, so i belive only getting the [Rapport nr] until i choose one, where I will load the data into the string and save it there for now) :)
my problem is that this wont work!
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
OBS: my error is now that it says i dont have any data in my rows or coloums
my code is as follows:
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output = "";
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Dato] FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
try
{
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
}
catch (Exception)
{
output = "fejl eller tom";
}
dbReader.Close();
Myconnection.Close();
label1.Text = output;
}
private void btnExport_Click(object sender, EventArgs e)
{
}
}
}
i figured this out :D after a break i went back to this and tried to see if there where enother method i could use and there was :P i figured by the error that it was properly something about the types so insted of taking one out and trying to work around that i took the hole row out and placed it in a object array :P by using GetValues in the dbReader i got it to work, so i can now move on :D for those who might be interested! here is my code :P its not pretty but it works :P i allso took in som try catch just to make sure i check for errors and getting a friendly respons on that :)
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output;
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Indlæsning Fuldført! Vælg venligst en rapport";
}
catch (Exception)
{
txtStatus.Text = "Indlæsning Fejlet!";
}
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
txtStatus.Text = "Du har valgt rapport nr.: " + aktuelRapportNR + "! Klik på export";
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT * FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
object[] liste = new object[dbReader.FieldCount];
if (dbReader.Read() == true)
{
int NumberOfColums = dbReader.GetValues(liste);
for (int i = 0; i < NumberOfColums; i++)
{
output += "|" + liste[i].ToString();
}
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Export Lykkes! Luk programmet!";
}
catch (Exception)
{
txtStatus.Text = "Export Fejlet!";
}
}
}
}

Categories

Resources