how get all records on database using mysql? - c#

I tried this:
MySqlConnection con = new MySqlConnection(...);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM questions;";
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int i = 0, len = reader.FieldCount;
while (i < len)
{
Response.Write(reader.GetString(i));
i++;
}
returns only the first values from table. how get all?
thanks in advance

You have to call reader.Read() until it returns false.
I've also taken the liberty of converting your inner loop to a for loop.
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Response.Write(reader.GetString(i));
}
}
Read this to read up on the IDataReader : http://msdn.microsoft.com/en-us/library/system.data.idatareader.read.aspx

Related

Datatable C# Input string was not in a correct format

My code:
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
dt.Rows[i][1] = gtennha;
}
When I run code, I received an error. Please help me fix it.
Expected Type as Int32
If gtennha contains a number, you can parse it to an int. With more safeguards:
var gtennha = cmd.ExecuteScalar();
try
{
if(gtennha != null)
dt.Rows[i][1] = int.Parse(gtennha.ToString());
else
Console.WriteLine("Error: Query didn't return a result.");
}
catch(FormatException ex)
{
Console.WriteLine("Error: Couldn't parse 'gtennha' to a number.");
/* more error handling */
}
Parse string to int
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha, out a);
dt.Rows[i][1] = a;
}
Update
if gtennha always start with VIOFFICE or a word something like that then use this way split string
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
String gtennha = cmd.ExecuteScalar().ToString();
int a;
int.TryParse(gtennha.Split(' ')[1], out a);
dt.Rows[i][1] = a;
}
I think you have choosen the wrong column to assign the return value of your ExecuteScalar query. From your error message it is clear that the return value is a string "VI BUILDING 29BD" (or something like that) and you are trying to assing that value to the same column dt.Rows[i][1] that you have used as the source for the ID parameter. This of course cannot be correct.
So you need to identify what is the column that you want to assign the return value of the ExecuteScalar and take extra care on handling that return value that could be NULL if there is no match on the WHERE clause
DataTable dt = new DataTable();
mySqlDataAdapter.Fill(dt);
int socot = dt.Rows.Count;
for (int i = 0; i < socot; i++)
{
String dn = dt.Rows[i][1].ToString();
String gduan = "SELECT tennha FROM duannha WHERE id=#id";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = gduan;
cmd.Parameters.AddWithValue("#id", dn);
object result = cmd.ExecuteScalar();
// SUPPOSE THAT YOU WANT TO ASSIGN AT COLUMN 2 NOT STILL AT COLUMN 1
if(result != null)
dt.Rows[i][2] = gtennha;
}

Storing fields from a database in an array c#

I am trying to store all fields from a column in my microsoft access database in an array. I am using OleDb but I don't really know how to go about doing this.
I know that I have to have a loop to go over the table the amount of times as there are rows in the table, but I don't know how to store the current field in the current index of the array.
Any help would be greatly appreciated!
Here is a snippet of some of the code:
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
for (int i = 1; i <= 10; i++)
{
//tasks[i] = current field in table
}
}
Sounds like you want something like this?
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader dataReader = cmd.ExecuteReader())
{
List<object[]> list = new List<object[]>();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
object[] oarray = new object[dataReader.FieldCount];
list.Add(oarray);
for (int i = 1; i <= dataReader.FieldCount; i++)
{
oarray[i] = dataReader[i];
}
}
}
}
}

Get entire table - MySQL error

Working with C# and MySQL here (Visual Studio 12 and MySQL workbench 6.1).
I'm trying to get the entire table into a list.
This is what I have so far:
List<Object> arrList = new List<Object>();
string str = #"server=localhost;database=test;userid=root;password=asd;";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
arrList.Add(reader["* "]);
}
When I pass SELECT * FROM emp; for query and try to get a toString of arrList, I get an indexOutOfBounds exception. (My table emp has 1 record in it.)
Thanks!
Edit: I'm trying to get the entire table (sequentially) into a list. Is this the right approach?
Edit 2: What if we don't know the number of columns in the table?
Change to:
while (reader.Read())
{
arrList.Add(reader["myColumnTitle"].ToString());
}
cause "* " isn't a valis columnname. alternative you can use an index
arrList.Add(reader[0].ToString());
for each Column:
List arrList = new List();
string str = #"server=localhost;database=test;userid=root;password=asd;";
string query = "SELECT * FROM emp";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var value = reader[i];
arrList.Add(Convert.ToString(value))
}
}
reader.Read() read your results row by row. That means inside this while statement, you need to read all columns of your query.
When you write "* ", your reader looks for a column named * which you don't have. MySqlDataReader can't understand to read all columns when you write * as you can in an sql query.
This should work.
while (reader.Read())
{
arrList.Add((string)reader[0]);
arrList.Add((string)reader[1]);
}
If you really don't know how many fields that your MySqlDataReader has, you can use SqlDataReader.FieldCount property.
Gets the number of columns in the current row.
So you code can be like;
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
Also use using statement to dispose your database connections and objects like;
using(MySqlConnection con = new MySqlConnection(str))
using(MySqlCommand cmd = con.CreateCommand())
{
...
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
}
}

Prevent duplicate entry in database

private void Save_Click(object sender, EventArgs e)
{
string strconn = #"Server=.\SQLEXPRESS;initial catalog=PharmacyV2;integrated security=true;";
SqlConnection conn = new SqlConnection(strconn);
//SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Units",conn);
da.Fill(ds, "Units");
bool found = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
conn.Close();
}
my program compare the each element from datagridview with every element from Uint table from database to prevent duplicate in database
if element from datagridvoew is not Similar to element in uint table in database
implement insert statement
Why the program does not insert any data to database?
(Does not implement the insert statement )
initialise your found variable to false inside your first for loop :
found = false;
so that it will be set to initial state for every iteration. otherwise if once it is set to true always becomes true.thats why yor insert statement is not getting executed.
So your for loop should look like :
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
found = false;
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (#name)", conn);
cmd.Parameters.AddWithValue("#name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
How about you ask the database to check if the entry exists?
var unitName = dataGridView1.Rows[i].Cells[0].Value.ToString();
var command = new SqlCommand("SELECT COUNT(*) FROM Units WHERE Unit_name = #name", connection);
command.Parameters.AddWithValue("#name", unitName);
int result = (int)command.ExectureScalar();
if(result == 0) // no entry
{
//Insert.
}

Trying to insert datagridview into SQL Server database

I am trying to import my datagridview data into my SQL Server database, But I am getting an error
Failed to convert parameter value from a DataGridView TextVoxCell to a variabletype
Can someone please guide me on a right path?
for (int r = 1; r < dataGridView1.Rows.Count; r++)
{
for (int c = 1; c < dataGridView1.Columns.Count; c++)
{
try
{
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftType) Values (#EmployeeID,#Date,#ShiftType", con);
query.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0];
query.Parameters.Add("ShiftType", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c];
con.Open();
query.ExecuteNonQuery();
}
}
}
Try adding Value to your cell, it's the property containing the information.
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;
Added .Value to my query Parameters. Inserting now works!
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{
for (int c = 1; c < dataGridView1.Columns.Count; c++)
{
try
{
SqlConnection con = new SqlConnection(constring);
SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftID) Values (#EmployeeID,#Date,#ShiftID)", con);
query.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
query.Parameters.Add("#Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;
query.Parameters.Add("#ShiftID", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c].Value;
con.Open();
query.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Categories

Resources