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.
Related
I have multiple row data in a single column. I need to save all data in to a MySQL DB. But it's only saving selected rows data only in DataGridView.
Below is my sample code.
private void button1_Click(object sender, EventArgs e)
{
string price = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price +"');";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = MySQLcmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Appreciate any help 🙂
Thank you!
One way is to use Foreach loop to get all rows value one by one in DataGridView and then insert them.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = "Connection String";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db1.table1 (price) VALUES (#price", con))
{
cmd.Parameters.AddWithValue("#price", row.Cells["ColumnName"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
If you want to save all rows from your Gridview then loop through it and pick up the column value to save.
Also if you want to save/update to the database, you should use ExecuteNonQuery. Finally, dispose of the objects you're creating and the reason for using.
using (MySqlConnection myConn = new MySqlConnection(MySQLConn))
{
myConn.Open();
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySqlParameter priceParameter = new MySqlParameter("#price");
MySQLcmd.Parameters.Add(priceParameter);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var price = row.Cells["PRICE_COLUMN_NAME"].Value;
MySQLcmd.Parameters["#price"].Value = price;
MySQLcmd.ExecuteNonQuery();
}
}
Dear mbharanidharan88 and user3501749, Thanks for quick support.
With your sup I fond a new code.
Below is my full working code (for me).
private void button1_Click(object sender, EventArgs e)
{
try
{
string MySQLConn = "datasource=localhost;port=3306;username=root;password=root;";
MySqlConnection myConn = new MySqlConnection(MySQLConn);
myConn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string price = dataGridView1.Rows[i].Cells[3].Value.ToString();
string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price + "');";
MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
MySQLcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If anything wrong let me know 🙂
I have a dropdownlist item named IsAuthor. It do not fill my textboxes by retrieving value from tblnewgroup table. Where is the problem I can not understand and it do not show any error please help me
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno='" + lstAuthor.SelectedItem.Value + "'";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
I filled my drop down list by these codes..
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT Groupname, Groupno FROM tblnewgroup";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["Groupname"].ToString();
newItem.Value = reader["Groupno"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
Problem : you are assigning single quotes to number feild Groupno.
Solution : you need to assign single quotes to VARCHAR Types only.
Suggestion: you are just assigning the values from SqlDataReader object without checking for rows.if the rows are not found then it will throw the Exeption. So i would suggest to Ceck the SqlDataReader object for any rows before assigning the values to TextBox Controls.
Try This:
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedValue;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
lblResults.Text = "Data Updated Successfully!";
}
else
{
lblResults.Text = "No Records found!";
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
It looks like you're selecting on a number field, but treating it like a text field. Modify your query to remove the single quotes:
selectSQL = "SELECT * FROM tblnewgroup ";
selectSQL += "WHERE Groupno=" + lstAuthor.SelectedItem.Value;
Also check the return value of reader.read() to see if there are any records:
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
else
{
lblResults.Text = "Author not found";
}
}
Note that I've put the reader in a using block to ensure it is closed, even if an exception occurs.
I assume SqlDataReader.Read method returns boolean value and you can use it like;
while(reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
Also I suspect lstAuthor.SelectedItem.Value is a number instead of a string. You might need to use it without using "".
Also using parameterized queries always a good choice.
selectSQL = "SELECT * FROM tblnewgroup WHERE Groupno = #Groupno";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#Groupno", lstAuthor.SelectedItem.Value);
....
Use following:
while (reader.Read())
{
txtGn.Text = reader["Groupno"].ToString();
txtgname.Text=reader["Groupname"].ToString();
txtsl.Text=reader["Slno"].ToString();
txtsn.Text = reader["Subname"].ToString();
}
void Main()
{
string connString;
connString = "Data Source=(local);Initial Catalog=Ochhi che guardano;Integrated Security=SSPI";
String sqlString;
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
sqlString = "SELECT Vare.varenavn";
sqlString += " FROM vare";
sqlString += " ORDER BY vare.varenavn";
SqlCommand cmd = new SqlCommand(sqlString, conn);
SqlDataReader reader =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
Console.WriteLine(reader.GetString(0));
}
reader.Close();
conn.Close();
}
catch (System.Data.SqlClient.SqlException e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I have this database, where i have a list of goods i need printed to a text file and saved and the heard drive. (vare = goods). But when i run this code, i get an error. My question is what i am doing wrong with this code and how i can save the list in a .txt file. I know how files are handled in C#, but not how to integrate it with my database.
I suspect that you are getting multiple rows back, and currently you are able to display only a single row. That is because you are not iterating through the reader. Try the following in place of you your if block.
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
If you want to store the data in a text file you can store each returned string in a list and then write that list to text file. So your code would be:
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
sqlString = "SELECT Vare.varenavn";
sqlString += " FROM vare";
sqlString += " ORDER BY vare.varenavn";
SqlCommand cmd = new SqlCommand(sqlString, conn);
SqlDataReader reader =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
List<string> strList = new List<string>();
while (reader.Read())
{
string temp = reader.GetString(0);
strList.Add(temp);
Console.WriteLine(reader.GetString(0));
}
reader.Close();
conn.Close();
//code to write list to text file
File.WriteAllLines(Application.StartupPath + "\\text.txt", strList.ToArray());
}
catch (System.Data.SqlClient.SqlException e)
{
Console.WriteLine(e.ToString());
}
I forget to return value in single tier application.
public int Studentid()
{
try
{
SqlConnection con = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = + ('" + Request.QueryString.ToString() + "')", con);
con.Open();
SqlDataReader dr = null;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
//Want help hear how I return value
}
con.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Here is a version of your method that achieves what you're after.
public int GetStudentId()
{
var sql = string.Format("SELECT s_id FROM student where name = '{0}'", Request.QueryString);
using (var con = new SqlConnection(connectionStr))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
var dr = cmd.ExecuteReader();
return dr.Read() ? return dr.GetInt32(0) : -1;
}
}
There's no need to use try/catch when you don't do anything with the exception except re-throw (and in fact you were losing the original stack trace by using throw ex; instead of just throw;. Also, the C# using statement takes care of cleaning up your resources for you in fewer lines of code.
IMPORTANT
Passing the query string directly into SQL like that means that anyone can execute random SQL into your database, potentially deleting everything (or worse). Read up on SQL Injection.
You should use using blocks, so that you are sure that the connection, command and reader are closed correctly. Then you can just return the value from inside the if statement, and doesn't have to store it in a variable until you have closed the objects.
You only have to open the connection once.
You should use parameterised queries, instead of concatenating values into the query.
public int Studentid() {
try {
using (SqlConnection con = new SqlConnection(connectionStr)) {
using (SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = #Name", con)) {
cmd.Parameters.Add("#Name", DbType.VarChar, 50).Value = Request.QueryString.ToString();
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
return dr.GetInt32(0);
} else {
return -1; // some value to indicate a missing record
// or throw an exception
}
}
}
}
} catch (Exception ex) {
throw; // just as this, to rethrow with the stack trace intact
}
}
The easiest way to return a single value is to call ExecuteScalar. You should also fix your SQL injection bug. And did you mean to encode the entire query string array, or just to pick out a single value?
public int StudentId()
{
string sql = "SELECT s_id FROM student WHERE name = #name";
using (var con = new SqlConnection(connectionStr))
{
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#name", DbType.VarChar, 256).Value = Request.QueryString["name"];
con.Open();
return (int)cmd.ExecuteScalar();
}
}
}
try this:
int s_id = (int) dr["s_id"];
int studId=0;
if(rdr.Read())
{
studId=rdr.GetInt32(rdr.GetOrdinal("s_id"));
}
if (dr.Read())
{
//Want help hear how i return value
int value = dr.GetInt32("s_id");
}
Like this?
public int Studentid()
{
int studentId = -1;
SqlConnection con = null;
try
{
con = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = + ('" + Request.QueryString.ToString() + "')", con);
SqlDataReader dr = null;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
studentId = dr.GetInt32(0);
}
dr.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if(con != null)
con.Close();
con = null;
}
return studentId;
}
i run this and i want to fill textbox txtFname with data - but it dont do nothing
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
txtFname.Text = dsView.Tables[0].Rows[3][0].ToString();
txtFname.DataBind();
Conn.Close();
}
how to do it ?
thank's in advance
using (Conn = new SqlConnection(Conect)) {
try {
// Attempt to open data connection
Conn.Open();
// Compose SQL query
string SQL = string.Format("SELECT * FROM MEN WHERE id = '{0}'", txtBAR.Text.Trim());
using(SqlCommand command = new SqlCommand(SQL,Conn)) {
// Execute query and retrieve buffered results, then close connection when reader
// is closed
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) {
// Assign txtFname value to search value and clear value if no results returned
txtFname.Text = reader.Read() ? reader[0].ToString() : string.Empty;
reader.Close();
}
}
}
finally {
// Regardless of whether a SQL error occurred, ensure that the data connection closes
if (Conn.State != ConnectionState.Closed) {
Conn.Close();
}
}
}
However, I would advise that you
update your SQL query to return the
actual column names instead of *
replace reader[0].ToString() with
reader["FirstName"].ToString()
using (Conn = new SqlConnection(Conect))
{
Conn.Open();
SQL = "SELECT * FROM MEN where id = '" + txtBAR.Text.Trim() + "'";
SqlCommand command= new SqlCommand(SQL,Conn);
SqlDataReader reader = command.ExecuteReader()
reader.Read();
//Call Read to move to next record returned by SQL
//OR call --While(reader.Read())
txtFname.Text = reader[0].ToString();
reader.Close();
Conn.Close();
}
Edit: I just noticed 'dataSet' not database, anyway you are reading third row, is your query returns more than one row?