What is the connection string if my database is host online, not in my local computer? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can WCF consuming data from database phpmyadmin?
I want to ask about the connection string that should i write at WCF. My database is host at phpmyadmin.
How should I write the connections string? if the database is using microsoft access or sqlserver that run at my computer, I done it already. Now, I'm curious if my database at phpmyadmin.
Honestly, I already asked this question in this forum yesterday. I say a big thanks to whom answer my question but I dont think that is a answer. I'm sorry for being stupid and don't understand what you said yesterday. If you get mad, you don't need to answer. thanks.
Out of the topic, this my WCF code.
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=127.0.0.1; Initial Catalog=mydatabase;User=ael;Password=123456;Integrated Security=False");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the wpf
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
I already create a user at phpmyadmin, and use it at my WCF. but whenever I run, its show "login failed for user ael".
Is there something I need to change in the connection string?
thanks before.

If I understand correctly you need an example for the connection string.
So for the connection string format please see ConnectionsStrings.com
For example, if you are using the standard port and did not change it:
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Then you can to use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here) and connect to the MySQL database programatically as explained in detail in this tutorial: Connection to the MySQL Server.

Related

changing value of cell on condition in gridview - c#

I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

How do I make a query to retrieve specific data

I am learning C# and SQL Server. I was following a simple tutorial, which led me to the creation of a class DBconnection that connects and updates the DB. Then I have a simple C# form that navigates back and forth on table rows using a button and a DataSet to clone the data, and then displays the info on some labels.
No problem 'till here, but then I thought, what if I wanted to display a single value(column) of a specific row, say "show me the last name of the person with a certain first name".
I'm familiar with the SQL query commands, so what I want is something like this:
SELECT last_name FROM Employees WHERE first_name = 'Jason'
Follows my code...
DBconnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cemiGEST
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
// variables
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
// set methods
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
// DataSet
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
// MyDataSet method
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
// Update DB method
public void UpdateDB(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
I am accessing the values (when moving back and forth) by just incrementing by one a variable that updates the row number. Some exemplifying code follows.
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = Properties.Settings.Default.authSQL;
ds = objConnect.GetConnection;
maxRows = ds.Tables[0].Rows.Count;
if (maxRows == 0)
{
MessageBox.Show("No user found. Loading first run wizard.");
NewUser newUser = new NewUser();
newUser.ShowDialog();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
I'm sure this is simple, but I'm not getting there.
EDIT:
I would prefer using my class DBconnection and without external libraries. I'm not at the PC with the project, so can't test anything right now, but after a good night of sleep over the matter, and after (re)looking at my code, I may have found the answer. Please tell me if you think this would do the trick:
In my second class (where I connect to and access the DB), I have already using a SQL query, more specifically here:
objConnect.Sql = Properties.Settings.Default.authSQL;
This query (authSQL), was created by me and embedded on the Settings, and here I am importing it. So, if I do the following instead, do you think it would work:
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
The "Properties.Settings.Default.authSQL" code is nothing more than a shortcut to a string "SELECT * FROM AUTH" - AUTH is my table, which I called Employees for the sake of simplicity.
So, it would be something like this:
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
ds = objConnect.GetConnection;
// Data manipulation here
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
There's no need for a dataset here. If you know the sql you want: use it - perhaps with some parameterization. For example, using "dapper", we can do:
string firstName = "Jason";
var lastNames = con.Query<string>(
"SELECT last_name FROM Employees WHERE first_name = #firstName",
new { firstName }).ToList();
Check this ....hope this also works...
//String Declaration
string Sqlstr = "select CountryCode,Description,Nationality from ca_countryMaster where isDeleted=0 and CountryCode = 'CAN' ";
string DBCon = "Data Source=RAJA;Initial Catalog=CareHMS;Integrated Security=True;";
SqlConnection SqlCon = new SqlConnection(DBCon);
SqlDataAdapter Sqlda;
DataSet ds = new DataSet();
try
{
SqlCon.Open();
Sqlda = new SqlDataAdapter(Sqlstr, SqlCon);
Sqlda.Fill(ds);
gdView.DataSource = ds.Tables[0];
gdView.DataBind();
}
catch (Exception ex)
{
lbl.text = ex.Message;
}
finally
{
ds.Dispose();
SqlCon.Close();
}

How can WCF consuming data from database phpmyadmin?

nice to meet you all. I'm new in here.
Just want to ask, how can my WCF consume data from database phpmyadmin?
I just tried my WCF consume data from database sqlserver and it works in my wpf app.
But I can't find a way how can my WCF access the data if my database is online.
is there any clue?
i try to change the data source into the IP at my database, it doesn't work.
here is my SqlConnection,
SqlConnection conn = new SqlConnection("Data Source=Alfred-PC;Initial Catalog=alfred;Integrated Security=True");
This is the WCF
public class Jobs : IJobs
{
SqlConnection conn = new SqlConnection("Data Source=Alfred-PC;Initial Catalog=alfred;Integrated Security=True");
SqlDataAdapter da;
DataSet ds;
Data data = new Data();
List<Data> listdata = new List<Data>();
public DataSet Details()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
conn.Close();
return ds;
}
public Data GetDetails(int jobid)
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data where id = " + jobid, conn);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
data.userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
data.firstname = ds.Tables[0].Rows[0][1].ToString();
data.lastname = ds.Tables[0].Rows[0][2].ToString();
data.location = ds.Tables[0].Rows[0][3].ToString();
ds.Dispose();
}
conn.Close();
return data;
}
public List<Data> GetAllDetails()
{
conn.Open();
ds = new DataSet();
da = new SqlDataAdapter("Select * from data", conn);
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
listdata.Add(
new Data
{
userid = Convert.ToInt32(dr[0]),
firstname = dr[1].ToString(),
lastname = dr[2].ToString(),
location = dr[3].ToString()
}
);
}
conn.Close();
return listdata;
}
}
this is the WPF file
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textbox1.Text.Trim().Length != 0)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
var x = jc.GetDetails(Convert.ToInt32(textbox1.Text));
if (x.userid != 0)
{
textbox2.Text = x.userid.ToString();
textbox3.Text = x.firstname;
textbox4.Text = x.lastname;
textbox5.Text = x.location;
}
else
MessageBox.Show("RecordNotFound ... !", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
MessageBox.Show("EnterID", "Message", MessageBoxButton.OK, MessageBoxImage.Warning);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.Details().Tables[0].DefaultView;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.JobsClient jc = new ServiceReference1.JobsClient();
dataGrid1.ItemsSource = jc.GetAllDetails() ;
}
}
If I understand correctly you need an example for the connection string.
So for the connection string format please look here: http://www.connectionstrings.com/mysql
An example could be Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; if you are using the standard port and did not change it. In this case you won't use integrated security though (you will specify the username and password in the connection string) so check if that is possible for you.
Then you may use the MySQL Connector (Namespace MySql.Data.MySqlClient downloadable here http://dev.mysql.com/downloads/dotnet.html) and connect to the MySQL database programatically as explained in detail here http://www.functionx.com/mysqlnet/csharp/Lesson02.htm
You're using integrated security. In the case of the WPF app, so the account used to authenticate access to the DB is the account you're logged in as. But in the WCF service, the account is controlled by the settings for the (IIS) server hosting it. You have some options:
Change to use a username and password to connect to the DB
Change the DB to accept the account that the WCF service is trying to connect as (the DB should tell you in an error message or log)
Change the server settings to use a Windows account that has privileges

SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. My forms code is as follows:
public partial class frmTimesheet : Form
{
private DataTable tableTS = new DataTable();
private SqlDataAdapter adapter = new SqlDataAdapter();
private int currentTSID = 0;
public frmTimesheet()
{
InitializeComponent();
}
private void frmTimesheet_Load(object sender, EventArgs e)
{
string strUser = cUser.currentUser;
cMyDate cD = new cMyDate(DateTime.Now.ToString());
DateTime date = cD.GetDate();
txtDate.Text = date.ToString();
cboTSUser.DataSource = cUser.GetListOfUsers("active");
cboTSUser.DisplayMember = "UserID";
cboTSUser.Text = strUser;
CheckForTimeSheet();
PopulateTimeSheet();
}
private void CheckForTimeSheet()
{
string strUser = cboTSUser.Text;
cMyDate cD = new cMyDate(txtDate.Text);
DateTime date = cD.GetDate();
int newTSID = cTimesheet.TimeSheetExists(strUser, date);
if (newTSID != this.currentTSID)
{
tableTS.Clear();
if (newTSID == 0)
{
MessageBox.Show("Create TimeSheet");
}
else
{
this.currentTSID = newTSID;
}
}
}
private void PopulateTimeSheet()
{
try
{
string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
"FROM tblTimesheetEntries " +
"WHERE TSID = " + this.currentTSID + ";";
SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
adapter.SelectCommand = sqlCom;
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Fill(tableTS);
dataTimesheet.DataSource = tableTS;
}
catch (Exception eX)
{
string eM = "Error Populating Timesheet";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
private void txtDate_Leave(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void cboTSUser_DropDownClosed(object sender, EventArgs e)
{
CheckForTimeSheet();
PopulateTimeSheet();
}
private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
adapter.Update(tableTS);
}
catch (Exception eX)
{
string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
cError err = new cError(eX, eM);
MessageBox.Show(eM + Environment.NewLine + eX.Message);
}
}
}
No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command.
Can anyone see what I am doing wrong?
What am I missing?
You need to set the UpdateCommand instead of SelectCommand on update:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The question is old, but the provided answer by#Anurag Ranjhan need to be corrected.
You need not to write the line:
adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
and enough to write:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
//remove the next line
//adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;
The Sql update/insert/delete commands are auto generated based on this line
SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
You can find the generated update sql by executing the line:
sqlBld.GetUpdateCommand().CommandText;
See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET
The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler.

Categories