I have tried many things, with no result. My question is, as the title says, how do I update a field in a database using SQL? Since I am a beginner with coding and SQL, I will copy my whole code below, not knowing what information you may need:
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;
using HPJFRMS;
namespace HPJFRMS
{
public partial class HomeFRM : Form
{
private string conn;
MySqlConnection connect;
string _naam = "";
Form _Loginfrm;
public HomeFRM(Form logFrom, string _name)
{
_Loginfrm = logFrom;
InitializeComponent();
lbWelkom.Text = "welkom " + _name;
_naam = _name;
}
private void HomeFRM_Load(object sender, EventArgs e)
{
tmCheck.Enabled = true;
}
private bool Todo_ophalen()
{
db_connection();
MySqlCommand cmdRead = new MySqlCommand();
cmdRead.CommandText = "SELECT `todo` FROM `user` WHERE `username` LIKE '" + _naam + "'";
cmdRead.Connection = connect;
MySqlDataReader tdOphalen = cmdRead.ExecuteReader();
if (tdOphalen.Read())
{
tbTodo.Text = tdOphalen.GetString(0);
connect.Close();
return true;
}
else
{
connect.Close();
return false;
}
}
private void db_connection()
{
try
{
conn = "Server=127.0.0.1;Database=users;Uid=root;Pwd=;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
finally
{
lbStatus.ForeColor = Color.Red;
}
}
private void btBewerk_Click(object sender, EventArgs e)
{
if (btBewerk.Text == "Bewerken")
{
tbTodo.ReadOnly = false;
btBewerk.Text = "Opslaan";
tmCheck.Enabled = false;
}
else
{
/* HERE COMES THE "UPDATE" CODE */
}
}
private void tmCheck_Tick(object sender, EventArgs e)
{
try
{
bool T = Todo_ophalen();
if (T)
{
lbStatus.ForeColor = Color.Green;
lbStatus.Text = "Online";
}
}
catch
{
lbStatus.ForeColor = Color.Red;
lbStatus.Text = "Offline";
}
}
}
}
There are different methods, you can use any of these.
Method 1: using simple SQL query
public void Update(Int UserId,String UserName )
{
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
string str = " UPDATE [dbo].[User] SET [UserName] = "+UserName +" WHERE [UserId] ="+ UserId+"";
SqlCommand cmd = new SqlCommand(str , con);
cmd.ExecuteNonQuery();
con.Close();
}
Method 2: using a stored procedure
First execute your stored procedure in database.
Example
CREATE PROCEDURE [dbo].[UpdateUser]
#UserId int,
#UserName varchar(25)
AS
BEGIN
UPDATE [dbo].[User]
SET [UserName] = #UserName
WHERE [UserId] = #UserId
END
public void Update(Int UserId,String UserName )
{
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
SqlCommand cmd = new SqlCommand("UpdateUser", con); //UpdateUser is the name of stored procedure you created
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("UserName ", UserName );
cmd.Parameters.AddWithValue("UserId", UserId);
cmd.ExecuteNonQuery();
con.Close();
}
Here is a sample method for an update:
public void UpdateUser(User userToUpdate)
{
try
{
string sqlStatement = #"UPDATE USERS " +
"SET DisplayName = #DisplayName, Username = #Username" +
"WHERE Id = #Id";
using (SqlConnectionconn = new SqlConnection("connection string here"))
using (SqlCommand cmd = new SqlCommand(sqlStatement, conn))
{
cmd.Parameters.Add(new SqlParameter("#Id", userToUpdate.Id));
cmd.Parameters.Add(new SqlParameter("#DisplayName", userToUpdate.DisplayName));
cmd.Parameters.Add(new SqlParameter("#UserName", userToUpdate.UserName));
cmd.ExecuteNonQuery();
}
}
catch (DbException ex)
{
throw ExceptionHandler.CreateSystemException(ex, ErrorStrings.DATABASE_ERROR);
}
}
This should get you started but you really need to read up on this subject as explaining the correct practices would be too long for an answer here.
this is maybe you need
MySqlConnection con = new MySqlConnection(conStr);
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(con);
cmd.CommandText = "UPDATE table_name SET field_name_1 = ?param1, field_name_2 = ?param2 WHERE id = ?id";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("?param1", value1);
cmd.Parameters.AddWithValue("?param2", value2);
cmd.Parameters.AddWithValue("?id", value3);
cmd.ExecuteNonQuery();
}
catch (MySqlException ee)
{
MessageBox.Show(ee.Message);
}
finally
{
con.Close();
con.Dispose();
}
Related
Hello I have good understanding on C and got a job for C# project but my knowledge on C# is poor. I started a project on C#. Project is billing and accounting software for resturants. I started doing login system. I used MSSQLocalDb.
In my login page i used ComboBox for UserID
Login page
When i click ComboBox it is empty
Problem
My youtube teacher's comboBox(Right one):
Right One
I don't know where is the problem please help dev friends...
I tried changing connection string didn't work
My connection code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Adisyon01
{
internal class cGenel
{
//public string conString = ("Server=(localdb)\\MSSQLLocalDB;Database=Restaurant2;Trusted_Connection=true");
public string conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Kerem Serinkan\\Restaurant2.mdf;Integrated Security=True;Connect Timeout=30";
public int _personelId;
}
}
My entry control code:
public bool personelEntryControl(string password,int UserId)
{
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee WHERE id=#Id AND PASSWORD=#password0", con);
cmd.Parameters.Add("#Id",SqlDbType.VarChar).Value = UserId;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
try
{
if(con.State==ConnectionState.Closed)
{
con.Open();
}
result = Convert.ToBoolean(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
throw;
}
return result;
}
My SqlDataReader code:
public void personelGetbyInformation(ComboBox cb)
{
cb.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cPersoneller p = new cPersoneller();
p._personelId = Convert.ToInt32(dr["id"]);
p._personelGorevId = Convert.ToInt32(dr["TASKID"]);
p._personelAd = Convert.ToString(dr["NAME"]);
p._personelSoyad= Convert.ToString(dr["SURNAME"]);
p._personelParola= Convert.ToString(dr["PASSWORD"]);
p._personelKullaniciAdi = Convert.ToString(dr["NICKNAME"]);
p._personelDurum = Convert.ToBoolean(dr["STATUS"]);
cb.Items.Add(p);
}
dr.Close();
con.Close();
}
I am creating a basic registration page using ASP.NET websites and C# and am trying to link the logins to a database I have created in Visual Studio 2017 and am constantly getting the error -
'System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Data.Common.DbCommand.ExecuteScalar(...) returned null.
and cannot understand why, code below any help appreciated.
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;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] WHERE UserName='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists, please enter a different username");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO Table (UserName,Email,Password,Country) values(#Uname ,#email , #password ,#country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Uname" , TextBoxUN.Text);
com.Parameters.AddWithValue("#email" , TextBoxEmail.Text);
com.Parameters.AddWithValue("#password" , TextBoxPass.Text);
com.Parameters.AddWithValue("#country" , DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}```
If you want to check if user exists, there's no need in ExecuteScalar() with value:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
when user doesn't exist, com.ExecuteScalar() returns null and you have a problem.
Code
private static bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) {
conn.Open();
//DONE: parametrized query
//DONE: 1 instead of * - we don't want all columns to be returned
string sql =
#"select 1
from [Table]
where UserName = #userName";
using (SqlCommand com = new SqlCommand(sql, conn)) {
com.Parameters.Add("userName", SqlDbType.VarChar).Value = userName;
// user exists if cursor is not empty (we have at least one record)
return com.ExecuteScalar() != null;
}
}
}
protected void Page_Load(object sender, EventArgs e) {
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack && UserExists(TextBoxUN.Text))
Response.Write("User already exists, please enter a different username");
}
I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.
I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
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.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.
I'm trying to add values into database, but every time I try to add some thing i get an error in the ExecuteNonQuery() with the message "Connection must be valid and open."
And I don't know what to do!!!
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 ClientesClinica
{
public partial class frmCadastro : Form
{
MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");
public frmCadastro()
{
InitializeComponent();
}
private void frmCadastro_Load(object sender, EventArgs e)
{
}
private void btnCancela_Click(object sender, EventArgs e)
{
Close();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
int cod;
string nome;
string end;
int tel;
cod = Convert.ToInt16(txtCodigo.Text);
nome = txtNome.Text;
end = txtEndereco.Text;
if (txtNome.Text == "")
{
MessageBox.Show("Favor digitar o nome");
}
if (txtCodigo.Text == "")
{
MessageBox.Show("Favor digitar o código");
}
conect.Close();
MySqlCommand insere = new MySqlCommand();
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
conect.Open();
insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
conect.Close();
MessageBox.Show("Salvo");
}
You need to open your connection and supply it to the command as per MSDN: SQLCommand
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection); //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Or for your usage:
conect.Open(); //<- Open Connection first
MySqlCommand insere = new MySqlCommand();
insere.Connection = conect; //<- Set the Commands connection
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
insere.ExecuteNonQuery();
conect.Close();
this exception often raise cause of call the ExecuteNonQuery() method before connection opening
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand command = con.CreateCommand();
command.CommandText="insert into stactoverflowtable (id,name) values('1','adil')";//suppose table name is stackoverflowtalbe
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}