how to store columns values in array in asp.net - mysql

I am writing code in asp.net. I have a column named c_name in database. I want to store all my columns values in an array. Here is my incomplete code. I am confused what to do here.
String str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
cmd.ExecuteNonQuery();
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (mdr.Read())
{
}
Please help.

Check below code:
String str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
List<string> list = new List<string>();
while (mdr.Read())
{
list.Add(mdr.GetString(0));
}
string[] strMyArray = list.ToArray<string>();

I suspect one of your your problems is this line:
cmd.ExecuteNonQuery();
You're actually executing cmd twice, once with this line and once again when you create your reader. I've also added a little code to copy the result into an element in a list. Try the following:
string str = "select c_name from contacts where user_id = " + user_id + "";
MySqlCommand cmd = new MySqlCommand(str, dbConnection);
MySqlDataReader mdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// create a list to hold the results in
List<string> results = new List<string>();
while (mdr.Read())
{
// for each row read a string and add it in
results.Add(mdr.GetString(0));
}
You've asked for an array - I've used a list because it's easier. If you REALLY want an array then just call:
var theArray = results.ToArray();
I would also suggest throwing in some using blocks around the connection, command and reader.

Related

how to display 2 tables from mysql in visual studio 17

this is in my controller
string connStr = "server=" + IpAddress + ";user=" + UserName + ";database=" + DatabaseName + ";port=" + PortNumber + ";password=" + Password + ";SslMode=none;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = " select * from Cities,Regions";
MySqlCommand com = new MySqlCommand(query, conn);
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
I use a view model for displaying data from mysql and i fill them as below.
List<Models.ViewModels.city> CT = new List<Models.ViewModels.city>();
SftpClient sftpclient = new SftpClient("port", "root", "name");
sftpclient.Connect();
foreach (DataRow item in ds.Rows)
{
city ct = new city
{
CityName = item.itemArray[1].ToString(),
CityNumber = Convert.ToInt32(item.itemArray[2])
}
region rg = new region
{
RegionName = item.itemArray[1].ToString(),
RegionNumber = Convert.ToInt32(item.itemArray[2])
}
}
CT.Add(ct);
return View(CT.ToList());
How could i show regions in my razor. i already used viewbag for sending a list form my region viewmodel. but it doesn't fill the viewmodel obviously but how should i fill the region viewmodel

asp.net:query with multiple where conditions

1. I have query.But couldn't add second where condition.Please suggest me the correct semantic .
2. And how can fetch the data from dropdownlist and show it in gridview.
3. How can i fetch value from Tution fee Column of my database when condition satisfies ,and Hostel Fee on fail of condition.??
protected void BindGridview()
{
constr = ConfigurationManager.ConnectionStrings["connstring_DETMIS"].ToString(); // connection string
// String FID = DropDownList1.SelectedItem.Value;
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(constr)) {
conn.Open();
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" + " where F_id =" + DropDownList1.SelectedItem.Value " and C_id=" + DropDownList2.SelectedItem.Value, conn)) {
using (var reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
gvDetails.DataSource = reader;
gvDetails.DataBind();
} else
lblWarning.Text = "There are no records..";
}
}
}
}
Welcome to Stackoverflow. You should first research on the google as why you are not able to add multiple conditions(It's just because of simple syntax mistake).
The exact code of line would be something like this.
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" +
" where F_id = '" + DropDownList1.SelectedItem.Value + "' and C_id=" + DropDownList2.SelectedItem.Value + "'", conn))
NOTE:- As a fellow developer, I won't suggest you to do this by passing values from here as it is dangerous and prone to SQL INJECTION
I would rather tell you to go by using Parameterized queries
Hope that helps and for future go for the Parametrized ones, as it is easy and technically preffered.
protected void BindGridview()
{
String strConnString = ConfigurationManager
.ConnectionStrings["connstring_DETMIS"].ConnectionString;
String strQuery = "select * from student_details " +
"where F_id=#F_Id and C_id=#C_Id";
MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(strConnString);
MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Parameters.AddWithValue("#F_Id",
DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#C_Id",
DropDownList2.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}

import csv and xls for bulk upload of user to register in a website

i am developing a website and i want to register the school children in a bulk way as they will provide the excel sheet and want that when i upload that sheet it automatically register user in userinfo table
here is the code
if (Request.Files["FileUpload1"] != null && Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224446;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Planetskool-20130901224446.mdf;Database=DefaultConnection; Trusted_Connection=true;Persist Security Info=True";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [UserInfoID],[UserID],[GraphID],[UserLevelEnumId],[Title],[FirstName],[MiddleName],[LastName],[Birthdate],[Gender],[Email],[MobileNo],[Country],[Zipcode],[CountFollowers],[CountFollows],[CountFiles],[CountPhotos],[Quote],[AvatarURL],[isVerified],[VerificationCount],[UserEnumType],[UserCreatorId] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "UserInfo";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
your code like below
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there.
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
Debug.Write("SheetTitle = " + excelSheets[t]);
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
DataSet ds = new DataSet();
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
}
}

Bulk Insert into SQL Server 2008

for (int i = 0; i < myClass.Length; i++)
{
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
cmdB.Parameters.AddWithValue("#EngPosFT", Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters.AddWithValue("#RegNumber", myClass.GetValue(i));
cmdB.Parameters.AddWithValue("#EngFTAv", Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", drpClass.SelectedValue);
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
assuming myClass.Length is 60. This does 60 update statements. How can I limit it to 1 update statement. Please code example using the above code will be appreciated. Thanks
Tried using this
StringBuilder command = new StringBuilder();
SqlCommand cmdB = null;
for (int i = 0; i < myClass.Length; i++)
{
command.Append("UPDATE CumulativeTable SET" + " EngPosFT = " + Convert.ToInt32(Pos.GetValue(i)) + "," + " EngFTAv = " + Math.Round((engtot / arrayCount), 2) +
" WHERE RegNumber = " + myClass.GetValue(i) + " AND Session= " + drpSess.SelectedValue + " AND Form= " + drpForm.SelectedValue + " AND Class= " + drpClass.SelectedValue + ";");
//or command.AppendFormat("UPDATE CumulativeTable SET EngPosFT = {0},EngFTAv={1} WHERE RegNumber ={2} AND Session={3} AND Form={4} AND Class={5};", Convert.ToInt32(Pos.GetValue(i)), Math.Round((engtot / arrayCount), 2), myClass.GetValue(i), drpSess.SelectedValue, drpForm.SelectedValue, drpClass.SelectedValue);
}//max length is 128 error is encountered
Look at the BULK INSERT T-SQL command. But since I don't have a lot of personal experience with that command, I do see some immediate opportunity to improve this code using the same sql by creating the command and parameters outside of the loop, and only making the necessary changes inside the loop:
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
//I had to guess at the sql types you used here.
//Adjust this to match your actual column data types
cmdB.Parameters.Add("#EngPosFT", SqlDbType.Int);
cmdB.Parameters.Add("#RegNumber", SqlDbType.Int);
//It's really better to use explicit types here, too.
//I'll just update the first parameter as an example of how it looks:
cmdB.Parameters.Add("#EngFTAv", SqlDbType.Decimal).Value = Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", SqlDbTypedrpClass.SelectedValue);
for (int i = 0; i < myClass.Length; i++)
{
cmdB.Parameters[0].Value = Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters[1].Value = myClass.GetValue(i));
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
It would be better in this case to create a stored procedure that accepts a Table Valued Parameter. On the .NET side of things, you create a DataTable object containing a row for each set of values you want to use.
On the SQL Server side of things, you can treat the parameter as another table in a query. So inside the stored proc, you'd have:
UPDATE a
SET
EngPosFT = b.EngPosFT,
EngFTAv=b.EngFTAv
FROM
CumulativeTable a
inner join
#MyParm b
on
a.RegNumber =b.RegNumber AND
a.Session=b.Session AND
a.Form=b.Form AND
a.Class=b.Class
Where #MyParm is your table valued parameter.
This will then be processed as a single round-trip to the server.
In such scenarios it is always best to write a Stored Procedure and call that stored proc in the for loop, passing the necessary arguments at each call.
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataTableExample
{
class Program
{
static void Main(string[] args)
{
DataTable prodSalesData = new DataTable("ProductSalesData");
// Create Column 1: SaleDate
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "SaleDate";
// Create Column 2: ProductName
DataColumn productNameColumn = new DataColumn();
productNameColumn.ColumnName = "ProductName";
// Create Column 3: TotalSales
DataColumn totalSalesColumn = new DataColumn();
totalSalesColumn.DataType = Type.GetType("System.Int32");
totalSalesColumn.ColumnName = "TotalSales";
// Add the columns to the ProductSalesData DataTable
prodSalesData.Columns.Add(dateColumn);
prodSalesData.Columns.Add(productNameColumn);
prodSalesData.Columns.Add(totalSalesColumn);
// Let's populate the datatable with our stats.
// You can add as many rows as you want here!
// Create a new row
DataRow dailyProductSalesRow = prodSalesData.NewRow();
dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
dailyProductSalesRow["ProductName"] = "Nike";
dailyProductSalesRow["TotalSales"] = 10;
// Add the row to the ProductSalesData DataTable
prodSalesData.Rows.Add(dailyProductSalesRow);
// Copy the DataTable to SQL Server using SqlBulkCopy
using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = prodSalesData.TableName;
foreach (var column in prodSalesData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(prodSalesData);
}
}
}
}
}

Facebook C# SDKv6 How to Parse results of Multi Query FQL

I can successfully execute a multi query fql using the facebook c# sdk v 6.14 thanks to Prabir's blog, but need help in parsing the results. I've searched and tried many ways to no avail. I know it is a simple syntax issue, but I'm fairly new to c# and JSON.
Any help is much appreciated!
Thanks,
Chad
My Code:
var fb = new FacebookClient(this.FacebookAccessToken);
dynamic resultsMQFQL = fb.Get("fql",
new
{
q = new
{
friendsMovies = "SELECT page_id, uid FROM page_fan WHERE type='MOVIE' AND uid IN (SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY page_id",
movieDetails = "SELECT page_id, name, pic, fan_count, categories, genre, starring, release_date FROM page WHERE page_id IN (SELECT page_id FROM #friendsMovies) ORDER BY fan_count DESC",
}
});
Results:
{"data":[
{"name":"friendsMovies",
"fql_result_set":
[{"page_id":105638652803531,"uid":796419451},
{"page_id":113271808686307,"uid":796419451}]},
{"name":"movieDetails",
"fql_result_set":[
{"page_id":105638652803531,"name":"Fear and Loathing in Las Vegas"},
{"page_id":113271808686307,"name":"Fletch"}
]
}
]}
Attempt at parsing:
foreach (dynamic row in resultsMQFQL.data.fql_result_set)
Error:
'Facebook.JsonArray' does not contain a definition for 'fql_result_set'
Ok, figured it out...forgot I could try various combinations quickly while debugging in the immediate window...did I say I am fairly new at coding? :)
public void FBMQFQL()
{
var fb = new FacebookClient(this.FacebookAccessToken);
dynamic resultsMQFQL = fb.Get("fql",
new
{
q = new
{
friendsMovies = "SELECT page_id, uid FROM page_fan WHERE type='MOVIE' AND uid IN (SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY page_id",
movieDetails = "SELECT page_id, name, pic, fan_count, categories, genre, starring, release_date FROM page WHERE page_id IN (SELECT page_id FROM #friendsMovies) ORDER BY fan_count DESC",
}
});
//To access a direct value: resultsMQFQL.data[0].fql_result_set[0].page_id
var friendsMovies = resultsMQFQL.data[0].fql_result_set;
var movieDetails = resultsMQFQL.data[1].fql_result_set;
if (resultsMQFQL == null)
{
//return null;
}
else
{
//Construct the new, formated, merged datatable to store the results the way we want them
DataTable dtMyFriendsMovies = new DataTable();
dtMyFriendsMovies.Columns.Add("MovieID");
dtMyFriendsMovies.Columns.Add("FriendUserID");
foreach (dynamic row in friendsMovies)
{
//Add New DataRow to new DataTable
DataRow drRow = dtMyFriendsMovies.NewRow();
//Get various values from original JSON Friend List returned
drRow["MovieID"] = row.page_id;
drRow["FriendUserID"] = row.uid;
//Add New Row to New Resulting Data Table
dtMyFriendsMovies.Rows.Add(drRow);
}
//MovieDetails
DataTable dtMovies = new DataTable();
dtMovies.Columns.Add("movieID");
dtMovies.Columns.Add("name");
dtMovies.Columns.Add("pic");
dtMovies.Columns.Add("fan_count");
dtMovies.Columns.Add("genre");
dtMovies.Columns.Add("starring");
dtMovies.Columns.Add("release_date");
foreach (dynamic row in movieDetails)
{
//Add New DataRow to new DataTable
DataRow drRow = dtMovies.NewRow();
//Get various values from original JSON Friend List returned
drRow["movieID"] = row.page_id;
drRow["name"] = row.name;
drRow["pic"] = row.pic;
drRow["fan_count"] = row.fan_count;
drRow["genre"] = row.genre;
drRow["starring"] = row.starring;
drRow["release_date"] = row.release_date;
//Add New Row to New Resulting Data Table
dtMovies.Rows.Add(drRow);
}
//return dtMyFriendsMovies;
}
} //FB FQL