I have mysql Database and i want to read data from there in my web application with for loop instead of foreach loop.
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = "SELECT * FROM survey ORDER BY datetime DESC";
MySqlCommand com = new MySqlCommand(query, conn);
com.CommandTimeout = 0;
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
foreach (DataRow item in ds.Rows)
{
string unique = item.ItemArray[4].ToString();
var sur = db2.VoipSurveys.Where(a => a.UniqueId == unique).SingleOrDefault();
if (sur == null)
{
VoipSurvey vs = new VoipSurvey()
{
Date = Convert.ToDateTime(item.ItemArray[1]),
Point = Convert.ToInt32(item.ItemArray[2]),
CallerId = item.ItemArray[3].ToString(),
UniqueId = item.ItemArray[4].ToString(),
AgentNumber = item.ItemArray[5].ToString(),
AgentName = item.ItemArray[6].ToString(),
QueueNumber = item.ItemArray[7].ToString()
};
db2.VoipSurveys.Add(vs);
db2.SaveChanges();
}
}
I need reading data from specific index like reading data in mysql table from this Date until now. and i think my problem would be solved with for loop
You can use a DataView RowFilter also:
// Create a DataView
DataView dv = new DataView(dt);
dv.RowFilter = " (Date >= #" +
Dateyouwanttouse +
"# And Date <= #" +
DateTime.Now +
"# ) ";
Simply do this:
foreach (DataRowView rowView in dv)
{
DataRow row = rowView.Row;
// Do something //
}
Related
For several days I've been struggling to display data from the table in DataSet. When I do not put a condition in the WHERE, it displays the complete table, but only the rows in the table that meet the condition are required. If there are suggestions for a quicker view. Thanks a lot.
myConnectionString = pwput;
MySqlConnectionconpara = new MySql.Data.MySqlClient.MySqlConnection();
conpara.ConnectionString = myConnec DataSetionString;
try
{
conpara.Open();
if (conpara.State == ConnectionState.Open)
{
string waccoun1 = wnalog1.ToString();
string waccoun2 = wnalog2.ToString();
stringnupita = "SELECT * FROM book WHERE year=wyear AND account >=
waccount1 AND account <= waccount1";
MySqlCommandcmdnal = new MySqlCommand(nupita,conpara);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#year",
wyear);
MySqlDataAdapte radda = new MySqlataAdapter(cmdnal);
MySqlCommandBuildercbb = new MySqlCommandBuilder(adda);
DataSet dsd = new DataSet();
adda.Fill(dsd, "book");
conpara.Close();
if (dsd != null)
{
dataGridView1.DataSource = dsd;
dataGridView1.DataMember = "book";
Font = new System.Drawing.Font("Arial Unicode", 7);
dataGridView1.Font = Font;
{
You need to use parameters like so:
...
stringnupita = "SELECT * FROM book WHERE year=#year AND account >=
#waccount1 AND account <= #waccount2";
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#year",
wyear);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#waccount1",
waccount1);
MySqlCommand(nupita,conpara);cmdnal.Parameters.AddWithValue("#waccount2",
waccount2);
...
I am trying to build an application which searches all attributes step by step daily and monthly using the between statement. The daily queries run, but monthly dones't run.
The code:
if (libs.conn.con.State == ConnectionState.Closed) libs.conn.baglanti.Open();
string today = "select getdate()";
SqlCommand today1 = new SqlCommand(today, libs.conn.con);
string today2 = today1.ExecuteScalar().ToString();
string[] day = today2.Split(' ');
day[0] += " 00:00:00";
string dayy = (DateTime.Now.Day).ToString();
string month = (DateTime.Now.Month).ToString();
string year = (DateTime.Now.Year).ToString();
string[] combine = new string[] { "1." };
combine[0] += month + ".";
combine[0] += year + " ";
combine[0] += "00:00:00";
string totalmonth = "(SELECT SUM(para) FROM statistics where datee between '"+combine[0]+"' AND '"+today2+"')";
SqlCommand totalmoneymonthlyquery = new SqlCommand(totalmoneymonth, libs.conn.baglanti);
string totalmoneymonthlyresult = totalmoneymonthlyquery.ExecuteScalar().ToString();
textBox7.Text = totalmoneymonthlyresult.ToString();
use
combine[0]=today2
use first
you may get parameter error to pull data.
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
im working in mvc and use sql command to insert data to my
database.
what i try to do is insert into 2 tables which one of them
have the foreign key from the other.
how can i build my sql query to make a condition on insert
into the table Image, insert the id in the foreignkey column
in the table Content.
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(FileName)");
sql.Append("values (#FileName)");
SqlCommand cmd2;
System.Text.StringBuilder sql2 = new System.Text.StringBuilder();
sql.Append("insert into Code(Html,JsCode,Id_Img)");
sql.Append("values (#Html, #JsCode, #Id_Img)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("#FileName", SqlDbType.VarChar).Value = myfilename;
int FileId = (int)cmd.ExecuteScalar();
cmd2 = new SqlCommand(sql2.ToString(), cn);
cmd2.Parameters.Add("#Html", SqlDbType.VarChar).Value = mydiv;
cmd2.Parameters.Add("#JsCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd2.Parameters.Add("#Id_Img", SqlDbType.Int).Value = FileId;
cmd2.ExecuteNonQuery();
cn.Close();
}
I think you can use ExecuteScalar() instead ExecuteNonQuery() to get the Scope_identity() value from the server like below and add that FileId to the second query.
using (SqlConnection cn = new SqlConnection("your_connection_string"))
{
string sql1 = "insert into Image(FileName) values (#FileName); " +
"SELECT CAST(scope_identity() AS int)";
string sql2 = "insert into Code(Html,JsCode,Id_Img) values (#Html, #JsCode, #Id_Img)";
int FileId = 0;
using (SqlCommand cmd = new SqlCommand(sql1,cn))
{
cmd.Parameters.AddWithValue("#fileName", myfilename);
cn.Open();
FileId= (int)cmd.ExecuteScalar();
}
}
I am trying to do something relatively simple using IdbCommand to execute an insert query.
Here's the code:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (#Date, #User, #Type, #Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "#Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "#User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "#Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "#Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
But I keep getting a MySqlException with the message "Column 'Date' cannot be null".
All my selects work fine, it's just this insert that has a problem and I can't see an obvious problem with it.
The parameter is populated with a valid DateTime during runtime.
I thought it might be related to the fact that Date is a reserved word and needs backquotes, but that's what online tutorials recommend.
Any ideas?
Found it!
For some reason instead of #, it needs ?
So the working code is:
using (IDbConnection conn = DbHelper.GetConnection(DbConnString))
using (IDbCommand com = conn.CreateCommand())
{
com.CommandType = CommandType.Text;
com.CommandText =
String.Format(
"INSERT INTO {0} (`Date`, User, Type, `Comment`) VALUES (?Date, ?User, ?Type, ?Comment);",
TableName);
conn.Open();
var parameterDate = com.CreateParameter();
parameterDate.ParameterName = "?Date";
parameterDate.Value = entry.Date;
parameterDate.DbType = DbType.DateTime;
com.Parameters.Add(parameterDate);
var parameterUser = com.CreateParameter();
parameterUser.ParameterName = "?User";
parameterUser.Value = entry.User;
parameterUser.DbType = DbType.String;
com.Parameters.Add(parameterUser);
var parameterLogType = com.CreateParameter();
parameterLogType.ParameterName = "?Type";
parameterLogType.Value = entry.Type;
parameterLogType.DbType = DbType.Int32;
com.Parameters.Add(parameterLogType);
var parameterComment = com.CreateParameter();
parameterComment.ParameterName = "?Comment";
parameterComment.Value = entry.Comment;
parameterComment.DbType = DbType.String;
com.Parameters.Add(parameterComment);
com.ExecuteNonQuery();
}
While running the code it is giving error " Cannot find column [max]." but i have added the max and min column to the table in the dataset
MySql.Data.MySqlClient.MySqlConnection mycon = new MySqlConnection(GetConnectionString());
if (mycon.State != ConnectionState.Open)
{
string sqlCat = "SELECT * FROM out_of_mark_table";
string sqlProd = "SELECT * FROM scord_mark_table";
MySqlDataAdapter da = new MySqlDataAdapter(sqlCat, mycon);
DataSet ds = new DataSet();
try
{
mycon.Open();
da.Fill(ds, "out_of_mark_table");
da.SelectCommand.CommandText = sqlProd;
da.Fill(ds, "scord_mark_table");
}
finally
{
mycon.Close();
}
DataRelation relat = new DataRelation("CatProds", ds.Tables["out_of_mark_table"].Columns["test_id"], ds.Tables["scord_mark_table"].Columns["test_id"]);
ds.Relations.Add(relat);
DataColumn count = new DataColumn("Products (#)", typeof(int), "COUNT(Child(CatProds).test_id)");
DataColumn max = new DataColumn("Most Expensive Product", typeof(decimal), "MAX(Child(CatProds).total)");
DataColumn min = new DataColumn("Least Expensive Product", typeof(decimal), "MIN(Child(CatProds).total)");
DataColumn no=new DataColumn("No");
DataColumn IdCol = new DataColumn();
min.Caption = "min";
max.Caption = "max";
string expr = "max * min";
IdCol.ColumnName = "ID";
IdCol.DataType = Type.GetType("System.Int32");
IdCol.ReadOnly = true;
IdCol.AllowDBNull = false;
//IdCol.Unique = true;
IdCol.AutoIncrement = true;
IdCol.AutoIncrementSeed = 1;
IdCol.AutoIncrementStep = 1;
ds.Tables["out_of_mark_table"].Columns.Add(count);
ds.Tables["out_of_mark_table"].Columns.Add(max);
ds.Tables["out_of_mark_table"].Columns.Add(min);
ds.Tables["out_of_mark_table"].Columns.Add(IdCol);
DataColumn sum = new DataColumn("Sum of", typeof(int), expr, MappingType.Attribute);
**ds.Tables["out_of_mark_table"].Columns.Add(sum);**
IdCol.SetOrdinal(0);
GridView1.DataSource = ds.Tables["out_of_mark_table"];
GridView1.DataBind();
You have set the captions to "Max" and "Min", but the DataColumns's identifier is it's Ordinal or ColumnName. You have set the ColumnName via constructor to
"Most Expensive Product" and "Least Expensive Product"
So use
string expr = "[Most Expensive Product] * [Least Expensive Product]";
instead.