Right now this is just presenting a line of the database but I need to present more, if anyone knew how to help me i would be grateful
private static string extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
private static string getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
while (reader.Read() == true)
{
if (reader.GetString(1) == null)
{
return "\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " às: " + reader.GetDateTime(3);
}
else
{
return "\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros " + " às: " + reader.GetDateTime(3);
}
}
return "";
}
}
}
The supposed is to show all the information of the lines where the card number is equal to the inserted
The return statement is going to exit your function, which is why you only get one result. If you want multiple lines, you're going to need to build and return a collection (e.g., array, list, etc.) or use yield return . . . the collection is probably the most straight-forward approach.
If you want all of the results in a single string, you'll need StringBuilder.
Related
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
while (reader.Read() == true && result.Count <= 9 )
{
if (reader.GetString(1) == "0")
{ //+ "ficando assim com: " + reader.GetDecimal(3)
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
return result;
}
}
}
private static IEnumerable<string> extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
As I have is presenting me only the first 10 lines, but I need the last 10 by normal order, how do I do that?
If anyone can help me, I'd be grateful
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
// Let's remove unused conditions
while (reader.Read())
{
if (reader.GetString(1) == "0")
{
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
// HERE IS THE MAGIC
return result.TakeLast(10);
}
}
}
If you use an ORDER BY in the query you can make sure which records are returned, and you can use TOP to restrict the quantity of records returned, so something like
return getExtrato($#"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC");
will return the desired records, and then you just need to read all of them and reverse the result in your code (there are other possibilities, but that might be simplest for now).
I build the following SQL query dynamically:
StringBuilder query = new StringBuilder();
StringBuilder query2 = new StringBuilder();
if (ComboRuleType.Text.Equals("Standard"))
{
query.Append("select * from [dbo].[" + ComboRuleTableName.Text + "]" + " WHERE" + "\n");
query.Append("(" + "\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
query.Append(row.Cells[1].Value.ToString() + " " + row.Cells[3].Value.ToString() + " ");
}
else
{
query.Append(row.Cells[3].Value.ToString() + " ");
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query.Append("like " + "'%" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query.Append("= " + "'" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query.Append("like " + "'" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query.Append("like " + "'%" + row.Cells[5].Value.ToString() + "'" + "\n");
}
}
query.Append(")" + "\n");
return query.ToString();
}
After converting the above to Entity SQL, it looks like:
StringBuilder query = new StringBuilder();
StringBuilder query2 = new StringBuilder();
if (ComboRuleType.Text.Equals("Standard"))
{
query.Append("select value q1 from ");
query.Append(ComboRuleTableName.Text);
query.Append("s");
query.Append(" as q1 where " + "\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
if (row.Cells[1].Value.ToString().Equals("AND"))
{
query.Append("&&" + " " + "q1." + row.Cells[3].Value.ToString());
}
else
{
query.Append("||" + " " + "q1." + row.Cells[3].Value.ToString());
}
}
else
{
query.Append("q1." + row.Cells[3].Value.ToString());
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query.Append(" LIKE (" + "'%" + row.Cells[5].Value.ToString() + "%'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query.Append(" == (" + "'" + row.Cells[5].Value.ToString() + "'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query.Append(" LIKE (" + "'" + row.Cells[5].Value.ToString() + "%'" + ")" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query.Append(" LIKE (" + "'%" + row.Cells[5].Value.ToString() + "'" + ")" + "\n");
}
}
return query.ToString();
}
I construct another SQL query that contains INNER JOIN and I have looked EVERYWHERE but cannot find the equivalent translation of that SQL query to an Entity SQL query. I would really appreciate if you can help me out. The dynamic SQL query with INNER JOIN is as follows:
query.Append("SELECT * ");
query.Append("FROM [dbo].[membership] mm \n");
query.Append("INNER JOIN [dbo].[" + ComboRuleTableName.Text + "] xx \n");
query.Append("ON (mm.m_" + ComboRuleTableName.Text + "_id = xx.id) \n");
query.Append("WHERE xx.id IN ( \n");
query.Append("SELECT id from [dbo].[" + ComboRuleTableName.Text + "] \n");
query.Append("WHERE \n");
query.Append("mm.platform_name = '" + ComboRulePlatformName.Text + "' AND (\n");
for (int i = 0; i < dgvUpdateCriteria.RowCount; i++)
{
DataGridViewRow row = dgvUpdateCriteria.Rows[i];
if (i != 0)
{
query2.Append(row.Cells[1].Value.ToString() + " " + row.Cells[3].Value.ToString() + " ");
}
else
{
query2.Append(row.Cells[3].Value.ToString() + " ");
}
if (row.Cells[4].Value.ToString().Equals("Contains"))
{
query2.Append("like " + "'%" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("Equals"))
{
query2.Append("= " + "'" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("StartsWith"))
{
query2.Append("like " + "'" + row.Cells[5].Value.ToString() + "%'" + "\n");
}
else if (row.Cells[4].Value.ToString().Equals("EndsWith"))
{
query2.Append("like " + "'%" + row.Cells[5].Value.ToString() + "'" + "\n");
}
else
{
query2.Append(" \n");
}
}
query2.Append("))\n");
return query.Append(query2).ToString();
I NEED it to be in a string format. I later convert it from string to query format. I just do not know how the INNER JOIN syntax works with Entity queries.
Thank you.
Edit 1:
Here is how I convert that Query into Entity Framework Object Query:
string query = EntityPreview(); //EntityPreview() is the method that gives me Raw Entity SQL Query
var objctx = (context as IObjectContextAdapter).ObjectContext;
if (ComboRuleTableName.Text.Equals("system"))
{
ObjectQuery<system> standardList = objctx.CreateQuery<system>(query);
rulePreviewForm.dataGridViewCriteriaRulePreview.DataSource = standardList;
rulePreviewForm.Show();
}
One of the greatest things about EntityFramework is it builds SQL for you and allows you to manipulate objects instead of SQL. There are other libraries like Dapper that are quicker when using straight SQL if you have a choice. If you have to use EntityFramework, you would be better off writing Linq.
When using Linq instead of SQL, you can still build Dynamic queries using IQueryable. This allows you to build a query without pulling any data from the database up front.
Without knowing much about what you are trying to do with your application, I can only offer a few tips of things to try. In the answer below I am making some assumptions on the naming of how you have your entities set up.
For getting a list of memberships from the membership table, assuming your entity for that table is called Membership:
IQueryable<Membership> memberships = context.Memberships;
That is your
query.Append("SELECT * ");
query.Append("FROM [dbo].[membership] mm \n");
For your filters you will likely want to put them into a List.
From this point on is where the dynamic part of this comes in. If you have a table for your ComboRule named [ComboRuleTable1] and another called [ComboRuleTable2], but you have to query based on input from ComboRuleTableName.Text, you can do something like this.
var filters = new List<string>() { "name1", "name2" };
// Get which table you should join to
switch (ComboRuleTable1)
{
// Join to tables and get filtered data
case "ComboRuleTable1":
memberships = memberships.ComboRuleTable1.Where(x => filters.Contains(x.PlatFormName));
break;
case "ComboRuleTable2":
memberships = memberships.ComboRuleTable2.Where(x => filters.Contains(x.PlatFormName));
break;
default:
break;
}
// This pulls the data from the database
var result = memberships.ToList();
Some of this will vary on how your EntityFramework is set up.
I hope this helps.
My code seems correct. But when I add the Group keyword in the query it produces a message:
Incorrect syntax near the keyword 'Group'
but when I remove the Group keyword the program runs successfully.
private void CSRMaintReviewer_Load(object sender, EventArgs e)
{
this.MaintReviewertbl.DataSource = null;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["csrapps"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select " +
"EmailID_Reviewer, " +
"Reviewer_Name, " +
"Reviewer_Email, " +
"EmailID_TeamLead, " +
"TeamLead_Name, " +
"TeamLead_Email, " +
"Site, " +
"Business_Unit, " +
"Group, " +
"Station, " +
"Pkg_Department, " +
"Region, " +
"Account, " +
"Key_Field, " +
"EmailID_SiteManager, " +
"SiteManager_Name, " +
"SiteManager_Email, " +
"EmailID_SiteDirector, " +
"SiteDirector_Name, " +
"SiteDirector_Email, " +
"EmailID_President, " +
"President_Name, " +
"President_Email, " +
"Customer, " +
"Flag, " +
"CreatedBy, " +
"DateCreated, " +
"LastUpdatedBy, " +
"DateUpdated " +
"from dbo.tblCSRMaintReviewer ";
try
{
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
MaintReviewer reviewer = new MaintReviewer();
reviewer.EmailIDReviewer = reader["EmailID_Reviewer"].ToString();
reviewer.ReviewerName = reader["Reviewer_Name"].ToString();
reviewer.ReviewerEmail = reader["Reviewer_Email"].ToString();
reviewer.EmailIDTeamLead = reader["EmailID_TeamLead"].ToString();
reviewer.TeamLeadName = reader["TeamLead_Name"].ToString();
reviewer.TeamLeadEmail = reader["TeamLead_Email"].ToString();
reviewer.Site = reader["Site"].ToString();
reviewer.BusinessUnit = reader["Business_Unit"].ToString();
reviewer.Group = reader["Group"].ToString();
reviewer.Station = reader["Station"].ToString();
reviewer.PKGDepartment = reader["Pkg_Department"].ToString();
reviewer.Region = reader["Region"].ToString();
reviewer.Account = reader["Account"].ToString();
reviewer.KeyField = reader["Key_Field"].ToString();
reviewer.EmailIDSiteManager = reader["EmailID_SiteManager"].ToString();
reviewer.SiteManagerName = reader["SiteManager_Name"].ToString();
reviewer.SiteManagerEmail = reader["SiteManager_Email"].ToString();
reviewer.EmailIDSiteDirector = reader["EmailID_SiteDirector"].ToString();
reviewer.SiteDirectorName = reader["SiteDirector_Name"].ToString();
reviewer.SiteDirectorEmail = reader["SiteDirector_Email"].ToString();
reviewer.EmailIDPresident = reader["EmailID_President"].ToString();
reviewer.PresidentName = reader["President_Name"].ToString();
reviewer.PresidentEmail = reader["President_Email"].ToString();
reviewer.Customer = reader["Customer"].ToString();
reviewer.Flag = reader["Flag"].ToString();
reviewer.CreatedBy = reader["CreatedBy"].ToString();
reviewer.DateCreated = reader["DateCreated"].ToString();
reviewer.LastUpdatedBy = reader["LastUpdatedBy"].ToString();
reviewer.DateUpdated = reader["DateUpdated"].ToString();
string[] row = { reviewer.EmailIDReviewer, reviewer.ReviewerName, reviewer.ReviewerEmail, reviewer.EmailIDTeamLead, reviewer.TeamLeadName,
reviewer.TeamLeadEmail, reviewer.Site, reviewer.BusinessUnit, reviewer.Group, reviewer.Station, reviewer.PKGDepartment,
reviewer.Region, reviewer.Account, reviewer.KeyField, reviewer.EmailIDSiteManager, reviewer.SiteManagerName,
reviewer.SiteManagerEmail, reviewer.EmailIDSiteDirector, reviewer.SiteDirectorName, reviewer.SiteDirectorEmail, reviewer.EmailIDPresident,
reviewer.PresidentName, reviewer.PresidentEmail, reviewer.Customer, reviewer.Flag, reviewer.CreatedBy,
reviewer.DateCreated, reviewer.LastUpdatedBy, reviewer.DateUpdated };
reviewers.Add(reviewer);
}
MaintReviewertbl.DataSource = reviewers;
MaintReviewertbl.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
Its giving you an error because Group is a keyword(words that have a special meaning in SQL like Select and from). This Group is conflicting with Group By and you are using it as a column name. You should change your column name in the table to something like Groupname or GroupType anything that is not a keyword in SQL. This will solve the error.
Looks like you are having a column named Group, but it's a keyword So I suggest you to change the column name(if it will not need severe coding changes) or else simply enclose them in a pair of [], like this [Group]. Keep in mind its not a good practice to give such keywords for other purposes, they are already reserved for some other purposes
I want to calculate the column values in datagridview with same id ...
Kindly see the image here... To view image click here
I wrote the following code...
but it stores individual rows what in datagridview....
private void AddStockTable()
{
try
{
Sqlcon = objDB.DBConnection();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Query = "insert into tblStock (PurchaseId, CurDate,JewelID, Purity, Weight, Quantity, SupplierId,G916,G22ct,G90,Silver) values " +
" ('" + txtPurchaseId.Text + "','" + dateTimePicker1.Text + "','" + dataGridView1[0, i].Value.ToString() + "','" + dataGridView1[2, i].Value.ToString() + "' " +
", '" + lblTotalWeight.Text + "','" + lblQuantity.Text + "','" + lblSupplier.Text + "','" + lbl916.Text + "','" + lbl22.Text + "','" + lbl90.Text + "','" + lblSilver.Text + "') ";
Sqlcmd = new SqlCommand(Query, Sqlcon);
Sqlcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I want to store the values in database like the following output
ID QUANTITY
J0001 4
J0002 9
Kindly support me...
I am not sure what the posted code is summing. However, one simplistic approach to sum the totals as you describe could be done with a Dictionary of string for “JewelID” and an int to keep a sum of the quantity. Loop through the rows in the DataGridView and get the values from the “JewelID” column and the “quantity” column and add them to the Dictionary.
If a “JewelID” already exist In the dictionary, then the “quantity” value is added to the currently existing value to get a running total of the “Quantity” for that “JewelID”. After the code iterates through all the rows, the Dictionary is output to a multi-line text box on the form.
private void btnUpdateIDQty_Click(object sender, EventArgs e) {
Dictionary<string, int> IDCount = new Dictionary<string, int>();
string curId = "";
int curQty = 0;
int oldValue;
foreach (DataGridViewRow row in dgvPurchaseOrder.Rows) {
if (row.Cells["JewelID"].Value != null && row.Cells["Quantity"].Value != null) {
curId = row.Cells["JewelID"].Value.ToString();
int.TryParse(row.Cells["Quantity"].Value.ToString(), out curQty);
if (IDCount.ContainsKey(curId)) {
IDCount.TryGetValue(curId, out oldValue);
curQty += oldValue;
IDCount[curId] = curQty;
}
else {
IDCount.Add(curId, curQty);
}
}
else {
// one of the cells is null ignore
}
}
StringBuilder sb = new StringBuilder();
sb.Append("ID quantity totals" + Environment.NewLine);
foreach (KeyValuePair<string, int> pair in IDCount) {
sb.Append("JewelryID: " + pair.Key + " Total Qty: " + pair.Value + Environment.NewLine);
}
txtIDQuantity.Text = sb.ToString();
}
I'm using sql 2008 express edition and I'm trying to do a multiple row insert thru my C# application.
I've got around 100000 records that needs to be inserted.
Okay all goes well for the first 1000 records then I'm getting the error:
"The number of row value expressions in the INSERT statement exceeds the maximum allowed number of 1000 row values."
I looked at my column data type -> int, so that shouldn't be the problem.
I checked my code and I'm inserting in steps of 500 records.
So I googled it but couldn't find anything useful. Can somebody explain why I get this error and if possible how to solve it.
You can use the SQLBulkCopy class. Which supports batching, transactions and is more efficient than standard insert statements.
this is how my code handles the multi insert
var count = "SELECT COUNT(*) as rowcount FROM table_mysql GROUP BY id";
var countReader = Retrieve(count);
var countRows = 0;
try
{
while (countReader.Read())
{
countRows += int.Parse(countReader.GetValue(0).ToString());
}
}
catch (Exception ex)
{
Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message);
}
finally
{
if (countReader != null) { countReader.Close(); _crud.close_conn(); }
}
for (var a = 0; a < countRows; )
{
var sql = "SELECT id, traffic_id, dow, uu, imps, impsuu, otsw, otsm FROM table_mysql LIMIT " + a + ", " + (a + 500) + "";
var reader = Retrieve(sql);
try
{
var builder = new StringBuilder();
builder.Append(
"SET IDENTITY_INSERT table_mssql ON;INSERT INTO table_mssql(id, traffic_id, dow, uu, imps, impsuu, otsw, otsm) VALUES ");
while (reader.Read())
{
Application.DoEvents();
try
{
builder.Append("(" + reader.GetValue(0) + ", " + reader.GetValue(1) + ", " +
reader.GetValue(2) +
", " + reader.GetValue(3) + ", " + reader.GetValue(4) +
", " + reader.GetValue(5) + ", " + reader.GetValue(6) + ", " +
reader.GetValue(7) +
"), ");
}
catch (Exception ex)
{
Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message);
}
}
var sqlDB = builder.ToString(0, builder.Length - 2);
sqlDB += ";SET IDENTITY_INSERT table_mssql OFF;";
if (!InsertDB(sqlDB))
{
Log.LogMessageToFile("Import.cs -> table_mssql: No insert happend!");
}
}
catch (Exception ex)
{
Log.LogMessageToFile("Import.cs -> table_mssql: " + ex.StackTrace + " /n" + ex.Message);
return false;
}
finally
{
if (reader != null)
{
reader.Close();
_crud.close_conn();
}
}
a = a + 500;
}
I'm going to check the sqlbulkcopy. Maybe that is a better solution.
You can take that whole thing down to this:
var sql = "SET IDENTITY_INSERT table_mssql ON;"
+ "INSERT INTO table_mssql"
+ "(id, traffic_id, dow, uu, imps, impsuu, otsw, otsm)"
+ " SELECT id, traffic_id, dow, uu, imps, impsuu, otsw, otsm "
+ " FROM table_mysql;"
+ "SET IDENTITY_INSERT table_mssql OFF;";
if (!InsertDB(sqlDB))
{
Log.LogMessageToFile("Import.cs -> table_mssql: No insert happend!");
}
Also: you should know that Sql Server doesn't support MySql's LIMIT keyword. It uses TOP or ROW_NUMBER instead.