I want to make a connection from my project that using Telerik to the PostgreSql database. After that i will make the CRUD, but i always failed to make the connection. I had already try the telerik docs but it still failed. I'm using visual studio 2012 and Npgsql as the driver. And i want to make connection with entity data model. Please anyone help me. I need the real tutorial with this. I makes web project
Using system.configuration you can try to call the app.config file.
Try this one:
http://docs.telerik.com/data-access/deprecated/quick-start-scenarios/asp.net-mvc/quickstart-mvc-conn-string
How about this one:
App.config file:
configuration>
connectionStrings>
add name="npgsql" connectionString="User >ID=npg_username;Password=npg_password;Server=server_Ip_or_localhost;Database=np>g_dbname;timeout=1000;Pooling=False;
Pooling=false;INTEGRATED >SECURITY=False; CommandTimeout=120" providerName="Npgsql"/>
/connectionStrings>
/configuration>
Note: Add references npgdll to your project
TO YOUR CODE BEHIND:
using System.Configuration;
using Npgsql;
using System.Data;
private static DataSet GetTData(ref string msg)
{
String Query = Query = #"select column1,column2 from table1";
String connstr = ConfigurationManager.ConnectionStrings["npgsql"].ToString();
NpgsqlConnection cnn = new NpgsqlConnection(connstr);
NpgsqlDataAdapter adp = new NpgsqlDataAdapter(Query, cnn);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
msg = String.Empty;
return ds;
}
catch (Exception e)
{
msg = e.Message;
return ds;
}
finally
{
ds.Dispose();
if (cnn != null)
{
cnn.Close();
cnn.Dispose();
adp.Dispose();
}
}
}
To use this:
private void form_Load(object sender, EventArgs e)
{
String error = string.empty
DataSet ds = new Dataset();
ds= GetTData(ref error);
if(error!=string.empty )
{
MessageBox.Show(error);
return;
}
}
Related
When trying to edit the datagridview, an error appears "The CommandText property has not been properly initialized.". I read that some other stored procedure is needed, which as input parameters it takes the first name, last name and patronymic and phone number of the user and returns his id, if so, how to implement it on mysql link to the source: https://metanit.com/sharp/adonet/2.11.php , https://metanit.com/sharp/adonet/3.5.php
Program code:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SD = System.Data;
namespace DBredaction
{
public partial class Form1 : Form
{
DataSet ds;
MySqlDataAdapter adapter;
MySqlCommandBuilder commandBuilder;
string connectionString = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
string sql = "SELECT * FROM employee";
public Form1()
{
InitializeComponent();
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AllowUserToAddRows = false;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
// делаем недоступным столбец id для изменения
dataGridView1.Columns["Id"].ReadOnly = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
//public MySqlConnection mycon;
//public MySqlCommand mycom;
//public string connect = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
//public SD.DataSet ds;
//public MySqlCommand mycon2;otchestvo
private void button1_Click(object sender, EventArgs e)
{
try {
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
adapter = new MySqlDataAdapter(sql, connection);
commandBuilder = new MySqlCommandBuilder(adapter);
adapter.InsertCommand = new MySqlCommand("", connection);
adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#imia", MySqlDbType.VarChar, 50, "Имя"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#familia", MySqlDbType.VarChar, 50, "Фамилия"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#otchestvo", MySqlDbType.VarChar, 50, "Отчество"));
adapter.InsertCommand.Parameters.Add(new MySqlParameter("#telephon", MySqlDbType.VarChar, 11, "Телефон"));
MySqlParameter parameter = adapter.InsertCommand.Parameters.Add("#id", MySqlDbType.Int16, 0, "Id");
parameter.Direction = ParameterDirection.Output;
adapter.Update(ds);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MessageBox.Show("DB CONNECT");
connection.Close();
}
}
catch
{
MessageBox.Show("Connection lost");
}
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dataGridView1.Rows.Remove(row);
}
}
private void button5_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(row);
}
}
}
It doesn't work quite like that; if you're assigning a command builder to an adapter you don't then also set the XxxCommand DML properties yourself; the command builder does that from looking at the SelectCommand, working out the table schema and writing the queries.
I'd have the adapter at class level in a dedicated repository class, where the select, connstr and command builder are set:
//in the constructor of the repo class
_myDataAdapter = new MySqlDataAdapter("SELECT here", "connstr here");
_commandBuilder = new MySqlCommandBuilder(_myDataAdapter);
the fill code runs:
//in a GetData method of the repo class
DatTable dt = new DataTable();
_myDataAdapter.Fill(dt);
return dt;
and the relevant I/U/D commands can be triggered:
//in a SaveChanges(DataTable) method of the repo class
_myDataAdapter.Update(dt);
See https://www.devart.com/dotconnect/mysql/docs/Devart.Data.MySql~Devart.Data.MySql.MySqlCommandBuilder.html for more background info on the CB; their example code is based on a complete programmatic "fill, change, save" workflow so it's all in one method, but your workflow is essentially interrupted by the user needing to do the changes in the grid, hence breaking it up.
If you want to do it in one method, you can make your adapter, make your command builder and then set the I/U/D commands on the adapter by calling the relevant GetXxx on the command builder
Note that the command builder doesn't use stored procedures; that thing you've read about needing to make a stored procedure to update/insert data isn't the only way to save data to a db, and if you have created a sproc and are hoping to use it, forget a command builder; you'll have to do the command setup yourself
I have a need to connect to a report Interbase server and pull data from a table.
I have the following code, I am trying several options to make a successful connection to the server, however not able to do so. Could you please let me know what's wrong with my code. Or please point me to any article which shows a step by step approach to successfully connect to an Interbase server and pull data.
using System;
using System.Data;
using System.Data.Common;
using InterBaseSql.Data.InterBaseClient;
string connectionString = "server=remoteserver_ip_address;dataBase=C:\\test\\interbasedb\\database.gdb;User_Name=myusername;Password=mypassword;";
using (var connection = new IBConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from table rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
I suspect the issue is with the connection string. I tried changing the connection string several ways, but getting different error every time.
All errors below.
Client library - ibclient64 not found (I copied ibclient64.dll into the project folder, and this error was resolved)
Your user name and password are not defined. Ask your database administrator to set up a InterBase login.
connection rejected by remote interface
Unable to complete network request to host "remoteserver_ip_address". Failed to locate host machine. Undefined service gds_db/tcp.
I am able to connect to the same server using IBConsole application, Which I believe is a client software to connect to Interbase server (Like Management Studio for SQL Server, and WorkBench for MySQL and PGAdmin for PostgresSQL)
The Parameters I am using to connect to the Interbase Server using IBConsole are same as that of I am using in the C# code.
Report Server IP: remoteserver_ip_address
DataBase: C:\test\interbasedb\database.gdb
User Name: myusername
Password: mypassword
Partial breakthrough for above issue.
After several hours of trial and error, I was finally able to connect to the interbase server successfully using Embarcadero drivers.
I had to change the connectionstring to look as below for a successful connection.
server=remoteserver_ip_address;database=C:\test\interbasedb\database.gdb;user=myusername;password=mypassword
But now I am stuck with another issue. When I use a query like select * from some_table_which_doesnot_exists, I clearly receive a message that the Table is not found.
And when I use a query like Select * from a table_that_exists_in_the_db, I always get follow error.
Dynamic SQL Error
SQL error code - 804
SQLDA error (I believe SQLDA = SQL DataAdapter, because thats where the code it throwing error)
I went to the Embarcadero Error Codes List to see more information on this error and found the reason to be SQLDA missing or incorrect version, or incorrect number/type of variables.. I am stuck here not sure how to proceed further. Please help.
I think you are missing "PORT" details for connection to the interbase server instance.
You can try the below solution for the connection string. This has worked for me in my local machine.
static void Main(string[] args)
{
var cs = BuildConnectionStringBuilder().ToString();
try
{
using (var connection = new IBConnection(cs))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
using (var command = new IBCommand("select * from employee rows 1", connection, transaction))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
Console.WriteLine(string.Join("|", values));
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private static IBConnectionStringBuilder BuildConnectionStringBuilder()
{
var builder = new IBConnectionStringBuilder();
builder.UserID = "SYSDBA";
builder.Password = "masterkey";
builder.DataSource = "localhost";
builder.Database = AppDomain.CurrentDomain.BaseDirectory + "test-employee.ib";
builder.Port = 3050;
return builder;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1_3grupa
{
public partial class Form1 : Form
{
SqlConnection konekcija = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void buttonIzadji_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
string sqlUpit = "select * from Citalac";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
//MessageBox.Show("Greska");
}
}
private void buttonPrikazDGV_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
param.ParameterName = "#param1";
param.Value = numericUpDown1.Value;
string sqlUpit = "select * from Hotel where HotelID=#param1";
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
komanda.Parameters.Add(param);
try
{
konekcija.Open();
SqlDataReader dr = komanda.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView2.DataSource = dt;
}
catch (Exception)
{
MessageBox.Show("Greska");
}
finally
{
konekcija.Close();
}
}
private void buttonPrikazLV_Click(object sender, EventArgs e)
{
string sqlUpit = "select * from Hotel";
try
{
SqlCommand komanda = new SqlCommand(sqlUpit, konekcija);
SqlDataAdapter da = new SqlDataAdapter(komanda);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
ListViewItem listItem = new ListViewItem(row["HotelID"].ToString());
listItem.SubItems.Add(row["Naziv"].ToString());
listItem.SubItems.Add(row["Adresa"].ToString());
listItem.SubItems.Add(row["Telefon"].ToString());
listItem.SubItems.Add(row["Grad"].ToString());
listItem.SubItems.Add(row["Drzava"].ToString());
listItem.SubItems.Add(row["Kategorija"].ToString());
listView1.Items.Add(listItem); // Dodaje red u ListView
}
}
catch (Exception)
{
MessageBox.Show("Greska");
}
}
private void buttonIzadji2_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I use the following snippet to query a local SQL Server CE database in a .sdf file
try
{
using (SqlCeConnection sqlCe = new SqlCeConnection(ConfigurationManager.ConnectionStrings["logdbcs"].ToString()))
{
SqlCeCommand sqlCeCommand = new SqlCeCommand(#"SELECT * FROM logs", sqlCe);
sqlCe.Open();
var reader = sqlCeCommand.ExecuteReader();
Debug.WriteLine(reader.HasRows);
sqlCe.Close();
return "";
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
throw;
}
The database has 3 rows, but this query returns no rows at all. I do this from an ASP.NET application, while debugging from local machine.
You are most likely using DataDirectory in your connection string (which you hide from us), so look in the bin/debug folde for a copy of your database file.
Try this code.
Datatable dt = new Datatable();
try
{
using (SqlCeConnection sqlCeConn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["logdbcs"].ToString()))
{
SqlCeCommand sqlCeCommand = new SqlCeCommand(#"SELECT * FROM logs", sqlCeConn);
sqlCeConn.Open();
sqlCeDataAdapter losqlCeDataAdapter = new sqlCeDataAdapter(sqlCeCommand);
losqlCeDataAdapter.Fill(dt);
return dt;
}
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
throw;
}
I have retrieved data from Mysql database into a DataGridView1. Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. The cell maintains its previous value when i reload data and the database is not modified. For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data.SqlClient;
namespace PI.Gen
{
public partial class frmMain : Form
{
MySqlConnection Conn;
public frmMain()
{
InitializeComponent();
btnDisconnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
try
{
if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
{
MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
return;
}
Conn = new MySqlConnection(strConnect);
Conn.Open();
if (Conn.State.ToString() != "Open")
{
MessageBox.Show("Could not open database connection");
return;
}
btnDisconnect.Enabled = true;
btnConnect.Enabled = false;
btnLoadData.Enabled = true;
btnLoadClients.Enabled = true;
// btnSubmitClient.Enabled = true;
}
catch (Exception ex) // catch on general exceptions, not specific
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (Conn != null)
{
Conn.Close();
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
Conn.Close();
Conn = null;
btnDisconnect.Enabled = false;
btnConnect.Enabled = true;
btnLoadData.Enabled = false;
btnLoadClients.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_receipients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void btnLoadClients_Click(object sender, EventArgs e)
{
try
{
string CmdString = "SELECT * FROM t_clients";
MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks #RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty
private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
{
try
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
MessageBox.Show("Cell Updated");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not updateing your changes to the database. While you keep your connection open doesn't mean that this will automatically update your data.
First of all, don't keep your connection open. In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion.
The way you load data is correct.
You give the datagridview an DataSource which is a table from your DataSet. So changes made in the datagridview ARE saved to your DataSet but not to your database.
This is how you update your database
public void UpdateTable(DataSet ds)
{
using (MySqlConnection connect = new MySqlConnection(ConnString))
{
connect.Open();
MySqlDataAdapter adapt = new MySqlDataAdapter();
MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
adapt.Update(ds.Tables[0]);
}
}
Make sure, before you Update your database, you use datagridview1.EndEdit()
Also, you using, this will ensure a connection is closed again after completing that code, best is to always have it in a try-except.
You had struggles with connecting the database as it appears to be in the commends.
I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case.
I didn't want to report this question as duplicated, but now it kinda does look like this answer.
I would like to give code which I have tested in my application.I used it for button click event.
private void button3_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
string MyConnection2 = "server=localhost;user id=root;password=;database=k";
using (MySqlConnection conn = new MySqlConnection(MyConnection2))
{
using (MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
StrQuery = #"update s set Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch
{
}
}
I think it may help you
I'm filling gridview from mysql table
public void Init()
{
DataSet dataset = new DataSet();
dataset = FillGrid();
bindingSorce.DataSource = dataset.Tables[0];
gridControl1.DataSource = bindingSorce;
}
public static DataSet FillGrid()
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
try
{
DataSet dataset = new DataSet();
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataset);
}
else
{
return null;
}
newConnection.Close();
return dataset;
}
catch { return null; }
}
After any changes I'm trying to update mysql table
private void gridView1_RowUpdated(object sender, EventArgs e)
{
try
{
BindingSource bs = (BindingSource)gridView1.DataSource;
DataTable changes = ((DataTable)bs.DataSource).GetChanges();
if (changes != null)
{
bool asd = UpdateGrid(changes);
((DataTable)((BindingSource)gridView1.DataSource).DataSource).AcceptChanges();
}
}
catch { }
}
public static bool UpdateGrid(DataTable datatable)
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
//try
{
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cmb = new MySqlCommandBuilder(adapter);
//adapter.UpdateCommand = cmb.GetUpdateCommand();
//adapter.Update(datatable);
cmb.GetUpdateCommand();
adapter.Update(datatable);
}
else
{
return false;
}
newConnection.Close();
return true;
}
// catch { return false; }
}
And table realy updating, but if after that I'll call Init() then FillGrid() will return dataset with right columns, but without rows!(dataset.tables[0].Rows.count = 0). After restart programm filling will work true, but again updating will have the same effect
I started facing the same issue you post here after upgrading the version of MySQL database.
I have developed a C# application that querys a MySQL database and fills several datagrids using MySqlDataAdapter Fill() method. The database version in development environment was MySQL Server 5.1.38. When I installed the final database in the server, I used the latest release of the same version, MySQL Server 5.1.73.
When I started testing the application, I started getting exactly the same problem: whenever any change on the data was made via the datagrid, the database updated correctly, but after that, any datagrid in the application querying the database returned 0 rows. After searching on the web I found only two or three posts refering to the same issue, but with no answer. By now, the only way to get rid of it was uninstalling the upgrade 5.1.73 and installing the 5.1.38 version again.