I'm building an application with C# code.
This is a simple code for inserting values unto the database. I have successfully inserted the values but when I checked on the time column where I have used the datetimepicker, it would only show 0000-00-00 00:00:00. So my problem is, How can you insert time and date only into the database?
private void button1_Click(object sender, EventArgs e)
{
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
timeanddate.Format = DateTimePickerFormat.Custom;
timeanddate.CustomFormat = "MM dd yyyy hh mm ss"; timeanddate.Value.ToShortDateString();
string Query = "Insert into fillupform.fillupform (filename,instructor,time,score) values('" + this.filename.Text + "','" + this.instructor.Text + "','" + this.timeanddate.Text + "','" + this.score.Text + "');";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Saved");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
no need to use a MySqlDataReader
string constring = "Database=fillupform;Data Source=localhost;User Id=root;Password=''";
string Query = "INSERT INTO fillupform.fillupform (filename,instructor,time,score) VALUES (#filename,#instructor,#time, #score);";
using (MySqlConnection conDataBase = new MySqlConnection(constring))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase))
{
cmdDatabase.CommandType = CommandType.Text;
cmdDatabase.Parameters.AddWithValue("#filename", this.filename.Text);
cmdDatabase.Parameters.AddWithValue("#instructor", this.instructor.Text);
cmdDatabase.Parameters.AddWithValue("#time", this.timeanddate.Text);
cmdDatabase.Parameters.AddWithValue("#score", this.score.Text);
try
{
cmdDatabase.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Related
I am getting error:
Connection must be valid and Open c# Winform.
Here is my code, can anyone please help what is wrong in the below code?
public void NameSearch()
{
listBox1.Visible = true;
try
{
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string Lname = myReader.GetString(myReader.GetOrdinal("StudLname"));
string Fname = myReader.GetString(myReader.GetOrdinal("StudFname"));
string Mname = myReader.GetString(myReader.GetOrdinal("StudMname"));
string nameResult = Lname + ", " + Fname + " " + Mname;
listBox1.Items.Add(nameResult);
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You haven't open connection before use it, Open connection
conDataBase.Open();
Open the conn before read:
conDataBase.Open();
Like:
String constring = "datasource=localhost;port=3306;Initial Catalog = 'svms'; username = svms; password =svms2016CPU";
string query = "select * from studentinformation where StudLname='" + metroTextBox1.Text + "'";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
//
conDataBase.Open();
//
MySqlDataReader myReader = cmdDataBase.ExecuteReader();
This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?
These are the values i want to send to the data base
private void radButton1_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;";
string Query = "insert into rhms.reservation(no_table)values('" + this.comboBox1.SelectAll() + "');";
MySqlConnection condatabase = new MySqlConnection(constring);
MySqlCommand cmd = new MySqlCommand(Query, condatabase);
MySqlDataReader myread;
try
{
condatabase.Open();
myread = cmd.ExecuteReader();
MessageBox.Show("saved");
this.Refresh();
while (myread.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You need set correct info at query string. Now it`s incorrect. Data must separated by commas:
string Query = "insert into rhms.reservation(no_table) values " + this.comboBox1.Items
.Select(p=>string.Format("({0})",p.ToString()))
.Aggregate((p1,p2)=>p1 + "," + p2) + ";"
I've been working on this program where it will pull accounts out of the database and will display them in a textbox I got this working so far but it will only pull the account from my database on the first row. Here is my code :
string myConnection = "datasource=xxxx;port=3306;username=xxxx;password=xxxx!";
string Query = "select * from xxx.xxx;";
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
DataTable dt = new DataTable();
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sUsername = myReader.GetString("usernames");
string sPasswords = myReader.GetString("passwords");
nsTextBox1.Text = sUsername + ":" + sPasswords;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Also is there anyway so it will erase the old Username + Password and show the new one that is pulled?
Like this?:
nsTextBox1.Text += sUsername + ":" + sPasswords + Enviroment.NewLine;
Also, your TextBox needs to be multiline.
Must it be a TextBox? Why not use a ListBox?
I try to use an update query in my C# windows form application. I do not get any errors, it just seems not to save the data I try to update. Take a look at the code:
private void button2_Click(object sender, EventArgs e)
{
try
{
string myConnection = connection;
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.UpdateCommand = new MySqlCommand(" update users set username=" + textBox1.Text + " where username=" + username + " ", myConn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
DataSet ds = new DataSet();
myConn.Close();
MessageBox.Show("Changes has been saved.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The username is an string passed from another form (gridview) ..
I found an solution for this on the internet. What I cam up with is:
private void button2_Click(object sender, EventArgs e)
{
string myConnection = connection;
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand("UPDATE `users` SET username='Test' WHERE username='CurrentName' ", myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = cmdDataBase.ExecuteReader();
myConn.Close();
MessageBox.Show("Changes has been saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}