Connect to MySQL remotely with C# - c#

I have an assignment for IT at school, where I need to collect data for a database.
I made a C# app that allows user input, then stores it into mt database, problem being I can't seem to get it to connect.
I have a DNS: maliciouzzhd.ddns.net.
I have port 3306 open, and forwarded.
I just don't know what to do after this.
I am using XAMPP.
Here is my code:
string CommandText = $"INSERT INTO UserData (FirstName, LastName, BirthDay, BirthMonth, BirthYear, UserName, EMail, Password, Admin, IP) values ('{FirstNameInput.Text}', '{LastNameInput.Text}', {BirthDayInput.Text}, '{BirthMonthInput.Text}', {BirthYearInput.Text}, '{UserNameInput.Text}', '{EMailInput.Text}', '{PasswordInput1.Text}', 0, '{IPTextBox.Text}')";
string ConnectionString = "server=maliciouzzhd.ddns.net;database=***********;uid=***********;pwd=**************;";
using (var mysqlconnection = new MySqlConnection(ConnectionString))
{
mysqlconnection.Open();
using (MySqlCommand cmd = mysqlconnection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 300;
cmd.CommandText = CommandText;
object objValue = cmd.ExecuteScalar();
}
mysqlconnection.Close();
}
If anyone knows what I can do to get it to connect, that would be great.
Thanks
EDIT: Forgot to mention that this works on localhost, when I change Server=maliciouzzhd.ddns.net to Server=10.0.0.1 or Server=127.0.0.1, but I need it to be remote.

First of a add the mysql library.
Project->Add Reference->Browse the dll file.
then import the class by using
using MySql.Data.MySqlClient;
MySql Connection code :
MySqlConnection conn;
conn = new MySqlConnection("SERVER=server_name;DATABASE=database_name;UID=database_username;PASSWORD=database_password");
to open connection
conn.Open();
to close connection
conn.Close();

Related

How to connect SQLite with my C# application

i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}

cannot open database - requested by the login - why can't I connect to my DB?

I'm trying to insert some data into my DB (Microsoft SQL Server)
My connection does not open and I get this message:
Cannot open database \"[Sales and Inventory System]\" requested by the login. The login failed.\r\nLogin failed for user 'Mostafa-PC\Mostafa'.
here is my code:
public void InsertProduct(List<string> _myName,
List<int> _myAmount,
List<int> _myPrice, string _date)
{
string connectionString = #"Data Source=MOSTAFA-PC;Initial Catalog=[Sales and Inventory System];Integrated Security=True";
string query = #"INSERT INTO dbo.product(Name, Amount, Price, [date])
VALUES(#Name, #Amount, #Price, #Date);";
using (SqlConnection Con = new SqlConnection(connectionString))
using (SqlCommand Cmd = new SqlCommand(query, Con))
{
Cmd.Parameters.Add("#Name", SqlDbType.NVarChar);
Cmd.Parameters.Add("#Amount", SqlDbType.Int);
Cmd.Parameters.Add("#Price", SqlDbType.Int);
Cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Convert.ToDateTime(_date);
Cmd.Connection = Con;
Con.Open();
int recordsToAdd = _myName.Count();
for(int x = 0; x < recordsToAdd; x++)
{
Cmd.Parameters["#Name"].Value = _myName[x];
Cmd.Parameters["#Amount"].Value = _myAmount[x];
Cmd.Parameters["#Price"].Value = _myPrice[x];
Cmd.ExecuteNonQuery();
}
}
I've done everything and I've searched everywhere. I cannot figure out why.
It seems like you need to check below things to solve your error.
1. Check permission. User must have access to this Database. Most Important One
2. Also, It would be better to access App.config key to code side. So declare connection string in app.config and try to set like below.
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["keyname"]
3. You also need to try connecting the instance in SSMS and It should not be failed.
This Link can be helpful to you for more information.
The error is definitely permission related.
Check permission of the account on the instance and DB.
And make sure the DB really exists on the server. Sometimes, it complains about permission but DB doesn't even exist.

I cannot send/insert data into my new database table using Visual Studio

I am having trouble trying to send my data into my database.
Basically, I am using an ASP.Net Web form already implemented by Visual Studio 2012 (Professional). I have created an extra page called 'users.asps' with only three text boxes (username, full name and email). Then I also created a new database called 'Datatest.mdf' and added ONE table in the database called 'users' which includes three attributes: username (primary key), name and email.
Below is my code for the button on the page. Here is where I want to send all the inputted data into my database table.
protected void Button1_Click(object sender, EventArgs e)
{
string strun = Request.Form["username"];
string strna = Request.Form["name"];
string strem = Request.Form["email"];
OleDbConnection objconnection = null;
OleDbCommand objcmd = null;
string stringconnection = null;
string strSQL = null;
//connection string
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
objconnection = new OleDbConnection(stringconnection);
objconnection.ConnectionString = stringconnection;
objconnection.Open();
strSQL = "insert into users(username, name, email)values(?,?,?)";
objcmd = new OleDbCommand(strSQL, objconnection);
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#username", strun));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#name", strna));
objcmd.Parameters.Add(new System.Data.OleDb.OleDbParameter("#email", strem));
objcmd.ExecuteNonQuery();
//close connection
objconnection.Close();
Response.Write("Entered Successfully");
}
When I run the form however I am getting an error "OleDbException was unhandled by user code" then says "SQL Server does not exist or access denied" that has an arrow pointing at objconnection.Open();.
Despite where the error is located, I know the problem lies where my string connection is, I just don't know how I can fix it.
stringconnection = "provider=SQLOLEDB;data source=(LocalDb)\\v11.0;Initial Catalog=Datatest; Integrated Security=SSPI;";
For all your connectionstring propblems.
You want to take a look in the sql department of that website.
I think that SQLOLEDB provider doesn't understand the connection string required to use a LocalDB.
(The LocalDB is more recent than SQLOLEDB)
Try to use SQLNCLI11 (The Sql Server Native Client v11)
"provider=SQLNCLI11;data source=(LocalDb)\\v11.0;
Initial Catalog=Datatest; Integrated Security=SSPI;";
However, if you are in the initial stage of developping your application I really suggest to use the SqlClient classes like SqlConnection, SqlCommand etc and leave behind the OleDb and all its limitations. (Like no support for named parameters)
using System.Data.SqlClient;
......
stringconnection = #"Data Source=(LocalDb)\\v11.0;Initial Catalog=Datatest;
Integrated Security=SSPI;";
using(objconnection = new SqlConnection(stringconnection))
{
objconnection.Open();
strSQL = "insert into users(username, name, email)values(#username, #name, #email)";
using(objcmd = new SqlCommand(strSQL, objconnection))
{
objcmd.Parameters.Add(new SqlParameter("#username", strun));
objcmd.Parameters.Add(new SqlParameter("#name", strna));
objcmd.Parameters.Add(new SqlParameter("#email", strem));
objcmd.ExecuteNonQuery();
}
}
Response.Write("Entered Successfully");
Try to visit this link https://www.daniweb.com/software-development/csharp/threads/339949/how-to-establish-a-connection-with-sql-server-using-c
maybe it can help you on your database connection problem :)

How to add/edit/retrieve data using Local Database file in Microsoft Visual Studio 2012

I want to get into developing applications that use databases. I am fairly experienced (as an amateur) at web based database utilization (mysql, pdo, mssql with php and old style asp) so my SQL knowledge is fairly good.
Things I have done already..
Create forms application
Add four text boxes (first name, last name, email, phone)
Added a datagrid control
Created a database connection using 'Microsoft SQL Server Database File (SqlClient)'
Created a table with fields corresponding to the four text boxes.
What I want to be able to do now is, when a button is clicked, the contents of the four edit boxes are inserted using SQL. I don't want to use any 'wrapper' code that hides the SQL from me. I want to use my experience with SQL as much as possible.
So I guess what I am asking is how do I now write the necessary code to run an SQL query to insert that data. I don't need to know the SQL code obviously, just the c# code to use the 'local database file' connection to run the SQL query.
An aside question might be - is there a better/simpler way of doing this than using the 'Microsoft SQL Server Database File' connection type (I have used it because it looks like it's a way to do it without having to set up an entire sql server)
The below is inserting data using parameters which I believe is a better approach:
var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
cmd.Parameters.Add("email", SqlDbType.NVarChar);
cmd.Parameters.Add("phone", SqlDbType.NVarChar);
cmd.Parameters["firstName"].Value = firstName;
cmd.Parameters["lastName"].Value = lastName;
cmd.Parameters["email"].Value = email;
cmd.Parameters["phone"].Value = phone;
cmd.ExecuteNonQuery();
}
This is selecting data from database and populating datagridview:
var dt = new DataTable();
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"
using (var cn = new SqlCeConnection(connectionString )
using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
//resize the DataGridView columns to fit the newly loaded content.
yourDataGridView.AutoSize = true; yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
//bind the data to the grid
yourDataGridView.DataSource = dt;
}
}
This first example is an over view based upon how I think it will be easier to understand but this is not a recommended approach due to vulnerability to SQL injection (a better approach further down). However, I feel it is easier to understand.
private void InsertToSql(string wordToInsert)
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
string queryString = "INSERT INTO table_name (column1) VALUES (" + wordToInsert + ")"; //update as you feel fit of course for insert/update etc
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open()
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
connection.Close();
}
}
I would also suggest wrapping it in a try/catch block to ensure the connection closes if it errors.
I am not able to test this but I think it is OK!
Again don't do the above in live as it allows SQL injection - use parameters instead. However, it may be argued it is easier to do the above if you come from PHP background (just to get comfortable).
This uses parameters:
public void Insert(string customerName)
{
try
{
string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
connection.Open() SqlCommand command = new SqlCommand( "INSERT INTO Customers (CustomerName" + "VALUES (#Name)", connection);
command.Parameters.Add("#Name", SqlDbType.NChar, 50, " + customerName +");
command.ExecuteNonQuery();
connection.Close();
}
catch()
{
//Logic in here
}
finally()
{
if(con.State == ConnectionState.Open)
{
connection.Close();
}
}
}
And then you just change the SQL string to select or add!

Error While Adding DataSource in Data Connections

When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

Categories