Insert Data from a textbox into a database . c# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hello stack overflow you are my only hope, Its my first question here. I'm having problem with inserting things into a database from textboxes i searched throught it i tried everything it just doesnt work. Here 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 E_BANK
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_save_Click(object sender, EventArgs e)
{
//objekti per konektim me DBne
SqlConnection conn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
string query = "INSERT INTO Bank1(accref, deposit, psID) " +
"Values('" + accref + "', '" + deposit + "', '" + psID + "')";
}
}
}
//mbylle lidhjen me DB
conn.Close();
MessageBox.Show("Transition Updatet Sucessfully");
}
private void btn_reset_Click(object sender, EventArgs e)
{
tb_accref.Text = "";
tb_depamount.Text = "";
tb_personalID.Text = "";
lblamount.Text = "0";
}
private void btn_exit_Click(object sender, EventArgs e)
{
Close();
}
}
}

Try this way
private void btn_save_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True"))
{
using (SqlCommand sqlComm = new SqlCommand("INSERT INTO Bank1 (accref, deposit, psID) VALUES (#accref, #deposit, #psID)", sqlConn))
{
if (sqlComm.Connection.State == ConnectionState.Closed)
sqlComm.Connection.Open();
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
sqlComm.Parameters.AddWithValue("#accref", accref);
sqlComm.Parameters.AddWithValue("#deposit", deposit);
sqlComm.Parameters.AddWithValue("#psID", psID);
sqlComm.ExecuteNonQuery();
MessageBox.Show("Transition Updatet Sucessfully");
}
}
}

You need to actually run the INSERT command. Check out the ExecuteNonQuery method on the SqlCommand class.

EXECUTE Command missing
private void btn_save_Click(object sender, EventArgs e)
{
//objekti per konektim me DBne
SqlConnection conn = new SqlConnection(#"Data Source=desktop-ndocu0t\sqlexpress;Initial Catalog=MetinShop;Integrated Security=True");
conn.Open();
string accref = tb_accref.Text;
int deposit = Convert.ToInt32(tb_depamount.Text);
int psID = Convert.ToInt32(tb_personalID.Text);
//try all fields are string
string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', '" + deposit + "', '" + psID + "')";
//try last fields are numeric
//string query = "INSERT INTO Bank1(accref, deposit, psID) Values('" + accref + "', " + deposit + ", " + psID + ")";
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = query;
command.ExecuteNonQuery()
//mbylle lidhjen me DB
conn.Close();
MessageBox.Show("Transition Updatet Sucessfully");
}
private void btn_reset_Click(object sender, EventArgs e)
{
tb_accref.Text = "0";
tb_depamount.Text = "0";
tb_personalID.Text = "0";
lblamount.Text = "0";
}
private void btn_exit_Click(object sender, EventArgs e)
{
Close();
}

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.

How to add textbox data to a database?

I am making a school project and i need to put text input (name and gender) into a database. This database (the names and genders) then have to be shown in a listbox. The code i have at the moment is put below, how can i make it work? Thanks in advance!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
As i understand you just have to add a insert between button1.click and addToList process.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
Database Name : People
Table Name : Person
All Parts Image :

C# insert data into database windows form app

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
{
}
}
}

Timeout error when trying to connect to remote address database

I keep getting timeout error, only a few times my code works. I was reading in this forum that I had to use "using" before the mysql. So I tried adding it, but still no luck. Maybe I'm using it wrong? Left my last connection to database without "using" so you guys can see how it was at first
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 MySql.Data.MySqlClient;
namespace WindowsFormsApplication4
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
FillCombo();
}
void FillCombo()
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "select * from mudiw_test.Registration ;";
using (MySqlConnection conDatabase = new MySqlConnection(dbcon))
{
using (MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase))
{
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("Name");
comboBox1.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "select * from mudiw_test.Registration where Name='" + comboBox1.Text + "' ;";
using (MySqlConnection conDatabase = new MySqlConnection(dbcon))
{
using (MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase))
{
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("Name");
string sId = myReader.GetString("ID");
string sEmail = myReader.GetString("Email");
string sAddress = myReader.GetString("Address");
string sPhone = myReader.GetString("Phone");
string sVisits = myReader.GetString("Visits");
name.Text = sName;
id.Text = sId;
email.Text = sEmail;
address.Text = sAddress;
phone.Text = sPhone;
address.Text = sAddress;
visits.Text = sVisits;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedItem == "Mantenimiento")
{
int value;
if (Int32.TryParse(visits.Text, out value))
{
if (value < 3)
{
price.Text = "150";
total.Text = "150";
discount.Text = "0%";
}
else if (value >= 3 && value <= 6)
{
price.Text = "150";
total.Text = "127.50";
discount.Text = "15%";
}
else if (value >= 7)
{
price.Text = "150";
total.Text = "112.50";
discount.Text = "25%";
}
}
}
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string dbcon = "SERVER=IP;DATABASE=mudiw_test;UID=mudiw_test;PASSWORD=PASS";
string Query = "insert into mudiw_test.Registration (Name,ID,Email,Address,Phone) values('" + this.name.Text + "','" + this.id.Text + "','" + this.email.Text + "','" + this.address.Text + "','" + this.phone.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(dbcon);
MySqlCommand cmDatabase = new MySqlCommand(Query, conDatabase);
MySqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmDatabase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The timeout won't be related to the using statement; wrapping the connection in using simply ensures that the connection is disposed when you are done with it. A timeout likely means that you have network connectivity issues between your machine and the database or you've supplied the wrong server name.

Deleting row from table c#

I'm brand new to c# and am trying to figure out the delete and update portion of my table. I get the insert portion because I am not trying to select anything in my table prior to clicking a button. With the delete and update however, I am confused as to how a query pairs up to the selected row in my table. If anyone could point me in the right direction that would be great. I am using a dataset and GridControl in devexpress. I also have to make use of buttons to perform the events and will not be using the command fields within the grid. And I'm working on making my insert with parameters.
My list:
public partial class PatientList : XtraForm
{
public PatientList()
{
InitializeComponent();
}
private void PatientList_Load(object sender, EventArgs e)
{
SAConnection conn = new SAConnection("dsn={SQL Anywhere 10};uid=dba;pwd=sql;databasefile=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
SADataReader rdr = null;
string Query = "SELECT * FROM patient";
SADataAdapter da = new SADataAdapter(Query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
grdList.DataSource = ds.Tables[0];
try
{
conn.Open();
SACommand cmd = new SACommand(Query, conn);
rdr = cmd.ExecuteReader();
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
}
private void btnNewPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnEditPatient_Click(object sender, EventArgs e)
{
Edit editPat = new Edit();
editPat.Show();
}
private void btnDeletePatient_Click(object sender, EventArgs e)
{
PatientService ps = new PatientService();
ps.DeletePatient();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
The service class performing the operations:
public class PatientService
{
public void DataAccess()
{
}
public void CreatePatient(Patient patient)
{
SAConnection conn = new SAConnection();
SACommand cmd = new SACommand();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
cmd.Connection = conn;
cmd.CommandText = (#"INSERT INTO patient (patient_id, first_name, last_name, address, city, state, zipcode, phone, classification_id)
VALUES ('"
+ patient.PatientID + "','"
+ patient.FirstName + "','"
+ patient.LastName + "','"
+ patient.Address + "','"
+ patient.City + "','"
+ patient.State + "','"
+ patient.ZipCode + "','"
+ patient.Phone + "','"
+ patient.ClassificationID + "'); ");
cmd.ExecuteNonQuery();
conn.Close();
}
public void UpdatePatient()
{
}
public void DeletePatient()
{
SAConnection conn = new SAConnection();
conn.ConnectionString = ("dsn={SQL Anywhere 10};uid=dba;pwd=sql;DBF=C:\\Users\\Kbaker1\\Desktop\\Training1.db;");
conn.Open();
SACommand cmd = new SACommand("DELETE FROM patient WHERE patient_id = #patient_id");
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Just replace the INSERT sql statement with UPDATE
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
Delete:
DELETE FROM table_name
WHERE some_column=some_value;

Categories

Resources