How can WCF consuming data from database phpmyadmin? - c#

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

Related

Form closes with an error when working with the database

I am trying to make it so that when changing the value in the comboBox, the database is displayed in the dataGridview. Everything seems to work, but when you close the form it gives an error:
enter image:
Code:
namespace Cursach
{
public partial class VoucherForm : Form
{
public VoucherForm()
{
InitializeComponent();
}
public void VoucherCountry()
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.AllowDrop = false;
dataGridView1.ReadOnly = true;
DB dB = new DB();
SqlCommand command = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", dB.ConnectionSQL());
command.Parameters.Add("#nC", SqlDbType.VarChar).Value = comboBox1.SelectedValue;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
dB.OpenSQL();
adapter.SelectCommand = command;
adapter.Fill(table);
dataGridView1.DataSource = table;
dB.ClodeSQL();
}
private void VoucherForm_Load(object sender, EventArgs e)
{
this.countryTableAdapter.Fill(this.cursacDat.Country);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
VoucherCountry();
}
}
You have a DB class which is good to separate you database code from your user interface code. I moved the database code to retrieve the Country data to the DB class. Notice how the DB class knows nothing about the user interface and the user interface knows nothing about the database.
Database objects need to be closed and disposed. using blocks take care of this for you even if there is an error.
public class DB
{
private string ConStr = "Your connection string";
public DataTable GetCountryData(string nC)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(ConStr))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", cn))
{
cmd.Parameters.Add("#nC", SqlDbType.VarChar, 100).Value = nC;
cn.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
}
Then in the form.
private void OpCode()
{
if (comboBox1.SelectedIndex < 0)
{
MessageBox.Show("Please select a value in the drop down.");
return;
}
DB DataClass = new DB();
dataGridView1.DataSource = DataClass.GetCountryData(comboBox1.SelectedValue.ToString());
}

Database access from within asp.net C# web sitie

I have an asp.net web site I'm trying to develop and I have an issue loading data from a database. It worked fine in a C# WebForm App and I was wondering what i need to do to get it to work correctly in the asp.net project and bind the results to a dropdownlist to be selected from.
try
{
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "127.0.0.1",
InitialCatalog = "PIIMSDATA",
IntegratedSecurity = true
};
SqlConnection cs = new SqlConnection(connectionStringBuilder.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Book1 Order by ID", cs);
}
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
//DropDownList2.DataSource = ds.Tables[0];
//DropDownList2.DataTextField = "ID";
//DropDownList2.DataValueField = "ID";
//DropDownList2.DataBind();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
//MessageBox.Show(ex.Message);
}
}
There are many ways to do that. Here's an example that I've ever tried:
public string connectionString = "Data Source = YOUCANSEEONSQLSERVER; Initial Catalog = DATABASENAME; User Id = sa; Password = sqlpasswordifyouuse";
private void Valetin_Load(object sender, EventArgs e)
{
OPIDCB.ResetText();
ValetCB.ResetText();
SqlConnection sqlconn = new SqlConnection(pr.connectionString);
SqlCommand sqlselect1 = new SqlCommand("Select EmpID, EmpName from Employees.Employee where IDPosition = 'OP'", sqlconn);
sqlconn.Open();
SqlDataReader dr1 = sqlselect1.ExecuteReader();
while (dr1.Read())
{
ArrayList MyAL = new ArrayList();
ArrayList MyAL2 = new ArrayList();
MyAL.Add(dr1.GetString(0));
MyAL2.Add(dr1.GetString(1));
foreach (string s in MyAL)
foreach (string s2 in MyAL2)
{
OPIDCB.Items.Add(s + " " + s2);
}
OPIDCB.SelectedIndex = 0;
}
dr1.Close();
sqlconn.Close();
}
If you are confusing with that code, you can visit this link: What is the right way to populate a DropDownList from a database?
Hope this help.
You can create connection string in web.config and get this param to bind in dropdownlist
Try to this link :
http://www.c-sharpcorner.com/UploadFile/rohatash/binding-dropdownlist-with-database-and-display-data-in-gridv/

Update mysql database from datagridview selected row

i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client, which am able to get data from fullrowselect mode into those textboxes. now i want to update the database upon changes in the those textbox values. so far i've tried some process and gets my "entry saved" messageBox.show but nothing happens to database, so am hoping someone could help me out maybe am missing something thanks
public partial class frmMain : Form
{
MySqlConnection connection;
MySqlDataAdapter mySqlDataAdapter;
DataSet dt = new DataSet();
DataSet DS = new DataSet();
DataSet dg = new DataSet();
public frmMain()
{
InitializeComponent();
}
#region Main load
private void frmMain_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_Clients", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
kryptonDataGridView1.DataSource = DS.Tables[0];
kryptonDataGridView1.Columns[0].Visible = false;
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_msg_charge_Rate", connection);
DataSet dt = new DataSet();
mySqlDataAdapter.Fill(dt);
kryptonDataGridView2.DataSource = dt.Tables[0];
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_client_deposits", connection);
DataSet dg = new DataSet();
mySqlDataAdapter.Fill(dg);
kryptonDataGridView3.DataSource = dg.Tables[0];
}
}
//loads selected row data into textboxes
private void kryptonDataGridView1_DoubleClick(object sender, EventArgs e)
{
textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientCode"].Value.ToString();
txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientName"].Value.ToString();
txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["PostalAdd"].Value.ToString();
txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd1"].Value.ToString();
txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd2"].Value.ToString();
txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd3"].Value.ToString();
txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["ChargeRate"].Value.ToString();
txtboxTotalDepo.Text = kryptonDataGridView1.SelectedRows[0].Cells["TotalDeposit"].Value.ToString();
txtboxAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["AccountBal"].Value.ToString();
txtboxEntrydate.Text = kryptonDataGridView1.SelectedRows[0].Cells["EntryDate"].Value.ToString();
}
now i tried this method to update but doesn't update database
private void kryptonbtnUpdate_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
using (MySqlConnection Conn = new MySqlConnection(connectionString))
if (Conn.State.ToString() != "Open")
{
}
else
{
connection.Open();
}
try
{
DataTable changes = ((DataTable)kryptonDataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)kryptonDataGridView1.DataSource).AcceptChanges();
mySqlDataAdapter.Update(DS);
}
// adapter.Update(rowsToUpdate);
// mySqlDataAdapter.Update(DS);
MessageBox.Show("Entry Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is just a pseudocode of what you need to do
string cmdText = #"UPDATE t_pi_Clients
SET ClientName = #ClientName,
PostalAdd = #PostalAdd,
Telephone = #Telephone,
Fax = #Fax,
.... etc ....
WHERE ClientCode = #ClientCode";
using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ClientName", txtboxClientName.Text);
cmd.Parameters.AddWithValue("#PostalAdd", txtboxPostalAddress.Text);
....etc etc...
cmd.Parameters.AddWithValue("#ClientCode", textboxClientCode.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
{
// extract the code that loads DataGridView1 from the Form_Load
// and create a reusable method that you could call from here
}
}
First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.
Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
Call the ExecuteNonQuery to store the values.
If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)

Delete selected row from datagrid view and update mysql database in C#

m developing application for my office and in my application there is a datagrid view that linked to a mysql database. local users can update the database using datagridview but they cant delete any recodes. i want to implement a method that user's are select exact raw in the datagridview and delete it as well as delete the database record soon. i managed to make select and delete datagridview row using below code but it not update the database
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
and this is my connection string that i normally use to view the database data in datagrid view. i don't have good knowledge to combined these two.can someone please show me how to do that
my connection string
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=******;port=3306;password=***********;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from warit.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try this code
private void button60_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
int loannumber = dataGridView1.Rows[oneCell.RowIndex].Cells['index of loannumber column in datagridview'].Value; // assuming loannmber is integer
string username = dataGridView1.Rows[oneCell.RowIndex].Cells['index of username column in datagridview'].Value; // assuming username is string
/* Now create an object of MySqlConnection and MySqlCommand
* and the execute following query
*/
string query = string.Format("DELETE FROM table_name WHERE loannumber = {0} AND username = '{1}'", loannumber, username);
}
}
}
string connection = "server = URL; uid = user; pwd = password; database = database;";
using (MySqlConnection conn = new MySqlConnection(connection)) {
conn.Open();
string idLocRemv = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string removeVolCred = "DELETE FROM TableName WHERE ID = " + idLocRemv;
using (MySqlCommand command = new MySqlCommand(removeVolCred, fbcConn)) {
command.ExecuteNonQuery();
}
conn.Close();
}
Apply necessary exception handlers. (try catch finally)
Additionally, you will need to re-load DataGridView afterwards.

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

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.

Categories