How to read data from a mysql table in c#? - c#

When I start the program I always get this error: could not find specified column in results:firstname.
I changed "firstname" for any other column and it is giving me the same error. I have tested the connection also and the connection is properly written.
public partial class frmDashboard : Form
{
public frmDashboard()
{
InitializeComponent();
}
public frmDashboard(string user)
{
InitializeComponent();
MySqlConnection connect = new MySqlConnection("Server=localhost;Database=mydb;user=root;Pwd=carolle;SslMode=none");
MySqlCommand cmd = new MySqlCommand("select upper(customer.firstname) from mydb.customer where customer.email = '" + user + "';");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
lblusername.Text = dr.GetString("firstname");
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
thank you in advance.

That's due to your use of upper which changes the result set.
Using an alias with AS can fix this.
SELECT upper(customer.firstname) AS firstname FROM mydb.customer WHERE customer.email = '"+ user + "';"
Also you should be using parameters, not string concatenation, when creating queries for a wide variety of reasons including security and type safety.
If you prefer you can retrieve columns using indexes instead, changing
dr.GetString("firstname");
to
dr.GetString(0);
The column index corresponds to the ordering of columns in the SELECT statement.

Related

Delete Command C# + SQL Server

I'm performing a command to erase data from a DataGridView
But I can not make it work, I just want to select a line and erase it
In addition to programming a button that says "Delete" so that when you click on it, the selected data in the DataGridView will be deleted
I need really help
I am lost
My Table is "Person"
My Column is "ID"
Instances
{SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt;}
public string Del(int ID)
{
string ouk = "Delete Work";
try
{
cmd = new SqlCommand("Delete From Person Where = ID )", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
return ouk;
}
For Button Erase at DataGridView
private void buttondel_Click(object sender, EventArgs e)
{
MessageBox.Show(c.Del(TBID));
}
The issue is that your SQL query is malformed and that you're not passing the ID to the query:
"Delete From Person Where = ID )"
One side of the equality check is missing, and you have an unexpected closing bracket.
You should change your query to accept a parameter:
"Delete From Person Where ID = #id"
and then pass the parameter to your command:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
So it becomes:
try
{
using (cmd = new SqlCommand("Delete From Person Where ID = #id", cn))
{
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
I've taken the liberty of wrapping SqlCommand in a using statement so that it's disposed once we're done with it.

How to insert data into a database table using a SqlCommand

I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.

Database not storing information properly, stores info on different rows

The database is not storing information all on the same row. On the first page, when I click the button it records it and that's fine, it's stored. Then on the next page, when i click the button, it stores the information, but on a different row? Any solutions? Heres the problem, and code below.
PAGE 1
public void addInformationToDatabase()
{
string Sex = ddlGender.Text;
string Name = tbxName.Text;
string DOB = tbxDOB.Text;
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = Con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO [User] (GenderID,Name,DOB) VALUES(#Sex,#Name,#DOB)";
command.Parameters.AddWithValue("#Sex", Sex);
command.Parameters.AddWithValue("#Name", Name);
command.Parameters.AddWithValue("#DOB", DOB);
try
{
Con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
2ND PAGE
public void save()
{
string checkboxSelection = CheckBoxList1.SelectedItem.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand c = new SqlCommand();
c.Connection = Con;
c.CommandType = CommandType.Text;
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1)";
c.Parameters.AddWithValue("#Ans1", checkboxSelection);
try
{
Con.Open();
c.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
Any help appreciated
your first page needs to get the ID back following the insert and then your second page needs to do an update based on that ID, not a subsequent insert.
There are a lot of resources about getting ids back - e.g How to get last inserted id?
(I'm assuming the id field uniquely identifies your row)
first query -
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1); SELECT SCOPE_IDENTITY()";
...
int userID = (Int32) c.ExecuteScalar();
you'll need to pass that ID to your 2nd page and change the insert to be an update:
"UPDATE User] SET Ans1 = #Ans1 WHERE Id = #id";
you'll also need to add the id as a parameter
c.Parameters.AddWithValue("#id", userID);

SqlDataReader into List<> - Quickest way

When I am reading data from a sql db and want to add all the items into a list (ie. eonumlist) below. Do I need to specifically assign each field or can I mass assign this data? I'm doing this for a report and want to get the data quickly. Maybe I should use a dataset instead. I have 40+ fields to bring into the report and want to do this quickly. Looking for suggestions.
public static List<EngOrd> GetDistinctEONum()
{
List<EngOrd> eonumlist = new List<EngOrd>();
SqlConnection cnn = SqlDB.GetConnection();
string strsql = "select distinct eonum " +
"from engord " +
"union " +
"select 'zALL' as eonum " +
"order by eonum desc";
SqlCommand cmd = new SqlCommand(strsql, cnn);
try
{
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EngOrd engord = new EngOrd();
engord.EONum = reader["eonum"].ToString();
engord.Name = reader["name"].ToString();
engord.Address = reader["address"].ToString();
eonumlist.Add(engord);
}
reader.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
cnn.Close();
}
return eonumlist;
}
I do something similar storing data from a db into a combo box.
To do this i use the following code.
public static void FillDropDownList(System.Windows.Forms.ComboBox cboMethodName, String myDSN, String myServer)
{
SqlDataReader myReader;
String ConnectionString = "Server="+myServer+"\\sql2008r2;Database="+myDSN+";Trusted_Connection=True;";
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select * from tablename", cn);
using (myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cboMethodName.Items.Add(myReader.GetValue(0).ToString());
}
}
}
catch (SqlException e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
This connects to the database and reads each record of the table adding the value in column 0 (Name) to a combo box.
I would think you can do something similar with a list making sure the index values are correct.
Store the data as xml, then deserialize the xml to the list.

got trap, how to log in?

private void d_Load(object sender, EventArgs e)
{
string connstring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\it155.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection conn = new SqlConnection(connstring);
try
{
conn.Open();
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
}
catch (Exception)
{
}
}
given the start of the code which is written above, what i plan to do is to be able to log in using id number datatype varchar(11) in the sql database which was to be entered in the txtSnumber but aside that i cant figure out how to check whether the id number entered is correct or not and if it is correct, the information corresponding to that id number enetered is supposed to show in the their corresponding textboxes. please help me, thanks
Your sql statement is prone to SQL Injection. Is terrible practice to concatenate SQL like this. Instead do something like this:
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber =#User", conn);
get.Parameters.AddWithValue("#User",snumber);
Now, in order to check whether the record was found or not, you do this:
using(IDataReader reader = get.ExecuteReader())
{
if (reader.HasRows)
{
//information correct. Do something
}
}
You can check it by using a DataReader()
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
SqlDataReader myReader = get.ExecuteReader();
if (myReader.HasRows)
{
MessageBox.Show("ID is valid");
while (myReader.Read())
//Do something here
}
else
MessageBox.Show("Given ID is Invalid.");
EDIT:
While calling ExecuteReader() method you put the following argument inside it, so that when ever you close the connection the datareader also automatically closes.
SqlDataReader myReader = get.ExecuteReader(CommandBehavior.CloseConnection);

Categories