TypeInitializationException C# using mysql connection - c#

I have a web C# app, all tables were created on MSSQL Server, I need to use some data now on another server which uses MySql. I may overcome my problem with a simple web service, but I wanted to add MySql just for learning. Here is the code.
MySqlConnection con = new MySqlConnection("server=10.45..;user id=user;persistsecurityinfo=True;database=db;password=pass");
MySqlCommand cmd = new MySqlCommand("select * from izin", con);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds); **//typeinitializationexception was unhandled by user code**
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
cmd.Dispose();
I get TypeInitializationException was unhandled by user code error from adapter. I couldn't find any similar problem.

I found the solution.
You need to add a new user with sql codes. I added mine from menus and it sure doesn't work.
Here is the code.
GRANT ALL PRIVILEGES ON *.* TO 'root'#'192.168.1.%'
IDENTIFIED BY 'some_characters'
WITH GRANT OPTION;
FLUSH PRIVILEGES;

Related

Using MySql.Data with C# while not making a MySqlConnection

The reccomended way to use MySql.Data is to NOT use a MySqlConnection object; as explained in the documentation. This allows for the MySQl.Data API code to handle connection pooling correctly.
See: mySQL documentation
So, for example, this code Selects data with the connection string passed in as a parameter.
The MySqlConnection object is created in the background:
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter("select * from cfx_jobs", _mySqlConnectionString);
adapter.Fill(dataset);
return dataset;
I have looked around and I cannot find an example of how to Insert into the database without explicitly creating a MySqlConnection object.
Which method should I use?
This is how to do it.
MySqlHelper.ExecuteNonQuery(_mySqlConnectionString, sqlStatement);

How to fix SqlConnectionString.Open() exception, login failed

I'm trying to establish a SqlConnection in my C# application, the application was working fine with Oracle DB but I wish to connect it to MS SQL now. I've made the necessary code changes which are mentioned in the code section below. The issue is SqlConnectionString,Open() throws exception
In web.config file I've added the CONNECTIONSTRING value as "Server=TCP:myServerName,Port_No\myInstanceName;Database=myDataBase;User Id=Username;Password=Password;"
private DataSet FireQuery(SqlCommand command, String tablename)
{
SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
SqlDataAdapter adapter = new SqlDataAdapter();
conn.Open(); //Code throws exception here
command.CommandType = CommandType.Text;
command.Connection = conn;
adapter.SelectCommand = command;
DataSet ds = new DataSet();
adapter.Fill(ds, tablename);
conn.Close();
return ds;
}
Exception thrown is System.Data.SqlClient.SqlException:
Cannot open database "mydataBase" requested by the login. The login failed.
Login failed for user 'Username'.
The "cannot open database" error means the authentication succeeded but the database context could not be set. This indicates either database "myDataBase" does not exist on the instance (or is offline) or the user does not have permissions to use it. In the latter case, the script example below will allow the user to use the database and objects.
USE mydataBase;
--create a database user mapped to login of same name
CREATE USER Username;
--also GRANT permissions on objects used directly by application
GRANT SELECT ON TABLE dbo.YourTable TO Username;
Check the connection string in the config file (or wherever you are getting it and passing to "FireQuery". The Username or password is wrong.
Error is telling you that the username you are passing is "Username". Literally.
Are you sure it even exists an user with such a stupid username? (easy findable and bruteforceable)
Usually sql server connects with user "sa" or something like that, unless you create specific users on your own. I think you or someone else just copy pasted a connection string found in some online guide and didn't bothered to change username or password.

How to use local database .sdf in c# wpf?

I am trying to make a database application. I added local database from
add > new item > local database.sdf
In Server Explorer, I created a table in the database. But I am having trouble connecting to it.
I want to show all the data in a DataGrid.
My code:
string ConnectionString = #"Data Source=""c:\users\asus\documents\visual studio 2012\Projects\WpfApplicationLocalDB\WpfApplicationLocalDB\LocalDB.sdf""";
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
List<DataRow> lis = dt.AsEnumerable().ToList();
DataGridView.ItemsSource = lis;
But when I build it, Visual Studio finds conn.open(); error. A message says that
SqlException was unhandled by user
Please help...
Also, can anyone suggest a tutorial of how can I create a simple database application in C#? Please help.
If you're using a .sdf file, you're using Microsoft SQL Server Compact Edition (SQL Server CE).
When using SQL Server CE, you must use SqlCeConnection and SqlCeCommand classes - not SqlConnection and SqlCommand (those are for the "full", server-based versions of SQL Server)

Update database using SqlCeDataAdaptor

I populate a listview from a Dataset that accesses sqlserver in visual studio 2008 express edition. I've been trying to update the listview and database simultaneously.
SettingTxt.Text references a textbox
With the following code, I've been able to update the list view with the information entered into the textbox, but the same update is not performed in the database. If anyone can help me resolve this, I would greatly appreciate it. I know there are alot of forums online regarding this exact problem, but I can't seem to get it working.
thisConnection = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
thisConnection.Open();
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "UPDATE Patient SET Setting = \'" + SettingTxt.Text + "\' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')" ;
SqlCeDataAdapter adp = new SqlCeDataAdapter();
adp.UpdateCommand = cmd;
dataSet.Tables[0].Rows[0][2] = SettingTxt.Text;
adp.Update(dataSet);
Thanks in advance.
Moved from an answer:
What I currently have is:
SqlCeCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = "SELECT column FROM table WHERE id=0";
SqlCeDataAdapter adp = new SqlCeDataAdapter(cmd);
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
ds = dataS.getDataSet();
adp.Fill(ds, "Patient");
SqlCeCommand comm = thisConnection.CreateCommand();
comm.CommandText = "UPDATE table SET Setting = 'value' WHERE (PtID=0)";
adp.UpdateCommand = comm;
adp.Update(ds, "Patient");
And I'm not understanding all the tutorials I find. Thanks in advance.
Update:
Yet even something as simple as the following doesn't update the database:
SqlCeConnection thisConn = new SqlCeConnection("Data Source=AugMedDB.sdf;Password=");
String query = "UPDATE Patient SET Setting = 'TopyTruck' WHERE (PtID=0) AND (EquipID=1) AND (Control='Lever')";
thisConn.Open();
SqlCeCommand commd = new SqlCeCommand(query, thisConn);
commd.ExecuteNonQuery();
thisConn.Close();
Your UPDATE statement is not suitable for an Adapter.Update(), for that it needs parameters and must be aligned with the SELECT statement.
You could try to execute that Command directly (w/o the adapter) or create a better update statement (using the dataset designer ).
Update
After filling the dataset,
generate the other SQL statements with a CommandBuilder (I think it exists for SqlCe)
or use your use your own Update command without the adapter. Just call comm.ExecuteNonQuery()
Tip 1: It may help to create a temporary (WinForms) project and use the VS tools to "Add a Datasource". You can look in the Dataset designer how VS generates the commands etc.
Tip 2: There are other options available, like entity framework. Datasets are (becoming) an "end of life" tech.
Thank you so much for all your help. I actually found the source of the problem. I had multiple references to the database; one within my project and another copy in bin/debug. I was correctly updating the copy in bin/debug but I was looking at the copy in my project. Once I deleted all copies, other than the one in bin/debug, it all worked and made sense. Now I see the updates in the database in bin/debug/

OLEDB Connection problem in C#

I am working with C# windows application
and I am facing a problem with OLEDB connection to SQL SERVER 2008
my code is too simple:
I am trying to fill the datagridview from this query
string connString = "Provider=SQLOLEDB;Data Source=servername;Initial Catalog=DBname;Integrated Security=SSPI";
string query = "SELECT * FROM account";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
//DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView_FraudDetails.DataSource = bSource;
dAdapter.Update(dTable);
but I get the Following error in this line
//fill the DataTable
dAdapter.Fill(dTable);
"[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied."
The code was running well , but when I uninstalled the server and reinstalled it again it gave me that error
I tried to turn off the firewall but it doesn't work
any suggestion please
Are you using SQL Server Express? If so you need to make sure that it is configured to accept connections via either TCP/IP or named pipes. By default, SQL Server Express does not accecpt connections. See http://www.datamasker.com/SSE2005_NetworkCfg.htm (this page is specific to SQL Server 2005 but should apply to 2008 as well).
Go to SQL Server Configuration Manager (under All Programs > Microsoft SQL Server in start menu) and for your instance, make sure TCP/IP is enabled. It is disabled by default for a new install of SQL Server.

Categories

Resources