I am getting an error that i dont understand. I have a form where a new row has to be added when i press the button add. It has to check for the values in comboBox cb_Character and from comboBox cb_Talents. When i test it i get the error. Data too Long for column, however when i try it in Mysql i am able to do it. what is wrong?
private void btn_addTalent_Click(object sender, RoutedEventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=Lorena89;";
string Query = "SET foreign_key_checks = 0; INSERT INTO dark_heresy.learned_talents (Character_Name, Talent_Name) VALUES ('" + cb_Character + "','" + cb_Talents + "'); SET foreign_key_checks = 1; ";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Added Talent to Character");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
I found the error, i was missing the .Text
('" + cb_Character.Text + "','" + cb_Talents.Text + "');
Related
I'm getting "System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'" error while running the following code.
SqlConnection con = new SqlConnection(#"String_data");
public student_info()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string insert = "INSERT INTO Table VALUES('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(insert);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted successfully");
con.Close();
}
Please change the line. As you are only providing SQL Command and not providing connection i.e., server name, database name, user id and password.
SqlCommand cmd = new SqlCommand(insert);
To
SqlCommand cmd = new SqlCommand(con, insert);
You can learn here in SqlCommand Class
I am trying to update my SQL table each time a value is changed in a data grid but all the values are changing instead of the one cell. Can someone please point me in the right direction.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
MySqlConnection conDataBase = new MySqlConnection(connString);
MySqlCommand cmdDatabase = new MySqlCommand(" update test.studentInfo set " +
"name ='" + this.dataGridView1.SelectedRows[0].Cells[1].Value.ToString() + "'," +
"mobile ='" + this.dataGridView1.SelectedRows[0].Cells[2].Value.ToString() + "'" , conDataBase);
MySqlDataReader myReader;
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Saved");
conDataBase.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
I want to add a Serial No. on the first column in the MySQL table in my C# program. To do this automatically with every row entry, I need to count previous rows and '+1' with the result.
How to count numbers of rows present in a column in MySQL with C#?
This is the code I am using now:
private void button2_Click(object sender, EventArgs e)
{
string connection = "datasource=localhost;port=3306;username=root;password=root";
string Query = "insert into database.accounts (idaccounts,Name,EmailID,UserID,Password,DOB,Gender) values('" +3+ "','" + this.AddUserName.Text + "','" + this.AddEmail.Text + "','" + this.AddUserID.Text + "','" + this.AddPassword.Text + "','"+this.dateTimePicker.Text + "','" + Gender + "') ;";
MySqlConnection conData = new MySqlConnection(connection);
MySqlCommand cmdData = new MySqlCommand(Query, conData);
MySqlDataReader myReader;
try
{
conData.Open();
myReader = cmdData.ExecuteReader();
MessageBox.Show("User Added Successfully!");
while(myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to add the Serial No. in the idaccounts column automatically with every new entry.
I'm using textbox to insert the data to the database. However I don't want to insert null or empty value to the database. How can I use if-statement to check the textbox is empty? (which means if the textbox is empty, show a dialog to required user input data)
Here is my code:
private void submit_button_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;username=root;password=";
string Query = "INSERT INTO bug.bug (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "')";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can use string.IsNullOrEmpty or string.IsNullOrWhiteSpace methods for checking if string is empty or only containts white spaces.
You should also avoid joining query using +. Use paratrized queries better. Example.
Try like this:
if (string.IsNullOrWhiteSpace(MyTextBox.Text))
{
//some message
}
This will handle the whitespace also (if it is present in your text box.)
On a side note:
Your code is prone to SQL Injection. You should better try to use parameterized query to handle it.
Put this condition in the start of your method
if(string.IsNullOrWhiteSpace(TextBox1.Text))
{
MessageBox.Show("Empty value");
return;
}
Use like following. Hope it will solve your problem
if(!string.IsNullOrEmpty(txtYourTextBox.Text))
{
//Logic here if text box is not empty
}
Be ware of Sql Injection
private void submit_button_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(mytextBox))
{
MessageBox.Show("your message goes here");
return ;
}
string constring = "datasource=localhost;username=root;password=";
// insert with parameterised query
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("The Bug have been reported");
while(myReader.Read())
{
}
this.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
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.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.