how to display 2 tables from mysql in visual studio 17 - mysql

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

Related

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;
}
}

Exception Thrown in this block thats why page cannot be redirected

The operation has timed out
objdbconn.OpenConn()
msSQL = " select google_name,google_password from hrm_mst_temployee " & _
" where employee_gid='" & Session("employee_gid") & "'"
objOdbcDataReader = objdbconn.GetDataReader(msSQL)
If objOdbcDataReader.HasRows = True Then
objOdbcDataReader.Read()
Try
user_password = objcmnfunctions.HttpDecodeFilePath(objOdbcDataReader.Item("google_password").ToString)
Catch
radnote.Text = "Problem Occurred While Decoding Password"
radnote.Show()
connect = 0
End Try
user_name = objOdbcDataReader.Item("google_name").ToString
End If
objOdbcDataReader.Close()
objdbconn.CloseConn()
Try
Dim contactser As New ContactsService("test")
contactser.setUserCredentials(user_name, user_password)
Dim newEntry As New ContactEntry()
newEntry.Title.Text = "(L)" & cbocompanyname.Text & "-" & txtcontactpersonname.Text
Dim primaryEmail As New EMail(txtEmail_ID.Text)
primaryEmail.Primary = True
primaryEmail.Rel = ContactsRelationships.IsWork
newEntry.Emails.Add(primaryEmail)
Dim phoneNumber As New PhoneNumber(txtcountrycode.Text & "-" & txtcontacttelephonenumber.Text)
phoneNumber.Primary = True
phoneNumber.Rel = ContactsRelationships.IsMobile
newEntry.Phonenumbers.Add(phoneNumber)
Dim name As New Name
name.FullName = "(L)" & cbocompanyname.Text & "-" & txtcontactpersonname.Text
newEntry.Name = name
Dim ims As New IMAddress
ims.Primary = True
Dim feedUri As New Uri(ContactsQuery.CreateContactsUri("default"))
Dim createdEntry As ContactEntry = DirectCast(contactser.Insert(feedUri, newEntry), ContactEntry)
Dim value As String = createdEntry.ExternalIds.ToString
Catch
radnote.Text = "Problem in Accessing Google Account"
radnote.Show()
End Try
End Sub

how to store columns values in array in asp.net

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.

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++)
{
}
}

CSV file filled in data adapter is empty or not

private DataTable GetDataFromCSV()
{
System.Data.DataTable dtExecChanges = new System.Data.DataTable("exec_changes");
string dirName = Path.GetDirectoryName(sInputFileName);
using (OleDbConnection cn =
new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;" +
"Data Source=" + dirName + ";" +
"Extended Properties=\"Text;HDR=Yes;FMT=Delimited\""))
{
// Open the connection
cn.Open();
// Set up the adapter
using (OleDbDataAdapter adapter =
new OleDbDataAdapter("SELECT * FROM " + (sInputFileName.Substring(sInputFileName.LastIndexOf("\\") + 1)), cn))
{
adapter.Fill(dtExecChanges);
}
cn.Close();
}
When I fill my data table dtExecChanges it will error coz my CSV file is empty.
Is there a way to chck is the select query is actually fetching any rows b4 filling by data table??