I am trying to retrieve data from a MYSQL table that has 2 rows but, only the first row is returned. The SQL statement used is very simple sqlQuery = "SELECT * FROM table"
With the code below the class only returns the first value found
private ArrayList dbRead(String sqlQuery, String classQuery)
{
ArrayList dbCategoryResults = new ArrayList();
// *** CONNECT TO DATABASE
Console.WriteLine("** Database Connection: Connecting to database");
MySqlConnection dbConnection = new MySqlConnection(dbStringConnection);
try
{
dbConnection.Open();
Console.WriteLine("** Database Connection: Connected to database server");
// *** READ FROM DATABASE
MySqlCommand command = new MySqlCommand(sqlQuery, dbConnection);
MySqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
if (classQuery == "categories")
{
//String det = dataReader[1].ToString();
dbCategoryResults.Add(dataReader[1]);
Console.WriteLine("Found " + dbCategoryResults.Count);
return dbCategoryResults;
}
}
dataReader.Close();
command.Dispose();
dbConnection.Close();
}
catch (MySqlException e)
{
Console.WriteLine(e.ToString());
MessageBox.Show(e.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// CLOSE DATABASE
try
{
dbConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return null;
}
Its as simple as
// Always call Read before accessing data.
// Advances the MySqlDataReader to the next record.
// returns true if it finds a record
while (dataReader.Read())
{
// depending on your query
Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
}
if you want the number of rows you could always make use of a DataTable or even just use a count in the while loop. DataTable Example :
DataTable dt = new DataTable();
dt.Load(reader);
Console.WriteLine("Rows returned : " + dt.Rows.Count);
foreach(DataRow dr in dt.Rows)
{
Console.WriteLine(dr["SomeResultingColumn"]);
}
Related
I have Sqlite method that makes SELECT query:
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
SQLiteDataReader reader = sqCommand.ExecuteReader();
return reader.GetString(0);
}
} catch (Exception e) {
// do exception handling
}
I tried to get last inserted id:
sql = 'SELECT id FROM Pacients ORDER BY id DESC LIMIT 1';
I tried to di that like:
return reader.GetString(0);
it's throwing me down on exception "No current row"
After calling ExecuteReader you need to call Read to position on the first record of the dataset. Read returns true/false to inform you if there are records to read. So your code changes to
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
SQLiteDataReader reader = sqCommand.ExecuteReader();
if(reader.Read())
return reader.GetString(0);
else
return ""; // or whatever you want to return if no records are present
}
} catch (Exception e) {
// do exception handling
}
Said that, remember that if you want to retrieve just one column from a single row like you have in your query then it is better to use ExecuteScalar instead of ExecuteReader
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
object result = sqCommand.ExecuteScalar();
return result != null ? result.ToString() : "";
}
} catch (Exception e) {
// do exception handling
}
I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!
I would like to get the value from ms access database to the checkedListBox.
it works properly for the ComboBox and TextBox but I don't know how to do that with the checkedListBox_prodline or checkedListBox_owner. (I have only one value in the database field)
private void button_clone_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * from PPAPdatabase where [PSW ID]=" + txt_c_PSW_ID.Text + "";
OleDbDataReader dr = null;
dr = command.ExecuteReader();
while (dr.Read())
{
comboBox_PPAP.Text = (dr["Reason"].ToString());
checkedListBox_prodline.Text = (dr["Production Line"].ToString());
checkedListBox_owner.Text = (dr["Owner"].ToString());
txt_comment.Text = (dr["Comment"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred: " + ex.Message,
"Important Note",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
finally
{
connection.Close();
}
Any help would be greatly appreciated!
Take a look of CheckedListBox.SetItemChecked. In case your items are strings.
var productLine = dr["Production Line"].ToString();
for (var i = 0; i < checkedListBox_prodline.Items.Count; i++)
{
var item = checkedListBox_prodline.Items[i] as string;
checkedListBox_prodline.SetItemChecked(i, productLine == item);
}
I want to show all details of the member through the name selected in combo box..Im trying below given code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
con.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT FlatNo FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
tbOwnerName.Text = ((string)cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I understand that you need to get all column records from memberinfo table and display them in UI. For that, you need to use ExecuteReader instead of ExecuteScalar. I have implemented execute reader in below code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
using(SqlConnection connection = con )
{
connection.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT Top 1 Name,City FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
tbOwnerName.Text = dr["Name"].ToString();
tbOwnerCity.Text = dr["City"].ToString();
//similarly store other column values in respective text boxes or wherever you need to get it displayed.
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I have two controls in my winform ,that is textboxes and datagridview .textboxes data entered by user save in one table(purchase) and datagridview data entered is save in another table (purchasedetail).My problem is textboxes values are saving in purchase table but datagridview values are not saving to database.
here is my save button code:
private void SAVE(object sender, EventArgs e)
{
try
{
con.Open();
cmd = new SqlCommand("insert into Purchase(purchase_id,purchase_date,ref_no,total,total_wrds) values(#purchase_id,#purchase_date,#ref_no,#total,#total_wrds)", con);
cmd.Parameters.AddWithValue("#purchase_id", textid.Text);
cmd.Parameters.AddWithValue("#purchase_date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#ref_no", textrno.Text);
cmd.Parameters.AddWithValue("#total", texttotal.Text);
cmd.Parameters.AddWithValue("#total_wrds", textinwrds.Text);
cmd.ExecuteNonQuery();
foreach (DataGridViewRow row in datagrid.Rows)
{
if (!row.IsNewRow)
{
using(SqlCommand cmd11 = new SqlCommand("insert into Purchasedetail(product_id, product_name,qty,price,tax,discount,total)values(#product_id, #product_name,#qty,#price,#tax,#discount,#total)", con))
{
cmd11.Parameters.AddWithValue("#product_id", row.Cells[0].Value);
cmd11.Parameters.AddWithValue("#product_name", row.Cells[1].Value);
cmd11.Parameters.AddWithValue("#qty", row.Cells[2].Value);
cmd11.Parameters.AddWithValue("#price", row.Cells[3].Value);
cmd11.Parameters.AddWithValue("#tax", row.Cells[4].Value);
cmd11.Parameters.AddWithValue("#discount", row.Cells[5].Value);
cmd11.Parameters.AddWithValue("#total", row.Cells[6].Value);
cmd11.ExecuteNonQuery();
datagrid.Refresh();
//row.ReadOnly = true;
//clm.ReadOnly = true;
MessageBox.Show("Added Sucessfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I assume you want to save your DataGrid table to a table in your database. With this answer I recommend you to work with your data in datagrid, not textboxes, if it is not very necessary.
First I am explaining the code.
Since your temporary DG table will be "added" you need to clear it first. Then turn your itemssource into a table and it is ready to be saved. Use an adapter to update the table.
try
{
SqlCommand ClearTableCommand = new SqlCommand("delete from " + CurrentTableName + ";", myconnection);
ClearTableCommand.ExecuteNonQuery();
DataTable myDT;
DataView myview;
myview = (DataView)dataGrid1.ItemsSource;
myDT = myview.ToTable(CurrentTableName);
using (SqlDataAdapter Adapter1 = new SqlDataAdapter("select * from " + CurrentTableName + "", myconnection))
{
Adapter1.UpdateCommand = new SqlCommandBuilder(Adapter1).GetUpdateCommand(true);
Adapter1.AcceptChangesDuringFill = false;
Adapter1.AcceptChangesDuringUpdate = true;
Adapter1.Update(myDT);
}
}
catch (Exception ex)
{
System.windows.MessageBox.Show(ex.Message);
}