Connecting to a database in C# - c#

I feel like an absolute idiot. I've been trying to connect to a database I created for a few hours now and I can't seem to get it to connect. Here is my code.
string chooseMoodCmbBx = moodCmbBx.SelectedIndex.ToString();
string source = "Data Source='E:\\Documents\\Database\\MyDatabase.sdf';" +
"Password='password';" +
"Persist Security Info=False;";
SqlConnection conn = new SqlConnection(source);
try
{
conn.Open();
MessageBox.Show("Succesfully Connected");
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}

You have an SDF file, meaning that you connect to a Sql Compact not to Sql Server. You need to use the classes in the namespace System.Data.SqlServerCe
SqlCeConnection conn = new SqlCeConnection(source);
Also, I am not sure of this, but I think you don't need to have single quotes around values in the connection string
string source = "Data Source=E:\\Documents\\Database\\MyDatabase.sdf;" +
"Password=password;" +
"Persist Security Info=False;";

Related

WinFormApp won't connect to the database

No clue why this won't work. It has worked before.
I do have the connection string in the app.config as well. I get the MySqlException error saying unable to connect to any database.
I made sure the firewall wasn't stopping it and I opened the ports on my router. All the references are in place too. This should work.
string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
try
{
using (MySqlConnection Conn = new MySqlConnection(connString))
Conn.Open();
MessageBox.Show("DB Connected");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
try this code
string connetionString = null;
MySqlConnection cnn ;
connetionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";
cnn = new MySqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
MySQL Databases cannot be used in WinFormApp due to security risks on a remote server. MS SQL DB's are supported. I didn't know that and I see a lot of questions about this so if anyone can't connect this may be why.

How to connect to a xampp server to a c# gui app?

So i was trying to connect a c# gui app to a xampp sql server here's the code:
try
{
string connectionString = "Server = localhost:8080; database = blog; Uid=root;Pwd";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into logins(username,password) values('name','password')", conn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this is the code username is root and no password
but when the program starts it raises an exception saying:
Format of the initialization string does not conform to specification starting at index 52.
Whats causing this problem and how can i solve it?
Thanks in advance
SQLConnection class is used to connect to sqlserver and to Connect Mysql MySqlConnection will be used
you need to add MySql Library in your C# project.
using MySql.Data.MySqlClient;
Config
string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=pwd;";
Use
string connetionString =""; //get from config;
MySqlConnection cnn ;
cnn = new MySqlConnection(connetionString);

How to restore SQL Server backups using asp.net and C#?

How to restore SQL Server backup using C#?
try
{
string test = "D:\\backupdb\\05012017_130700.Bak";
sqlcmd = new SqlCommand("Restore database EmpolyeeTable from disk='D:\\backupdb\\05012017_130700.Bak'", con);
sqlcmd.ExecuteNonQuery();
Response.Write("restore database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
Quite weird requerement you have right there. I´ve never heard of someone restoring a database backup from a webpage, and as #Alex K. told, it would be quite rare that the user that uses your web application have the required previleges.
Anyway, supposing that everything told above is OK, the code to restore a backup would be this:
Use this:
using System.Data;
using System.Data.SqlClient;
Code:
private void TakeBackup()
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK' WITH REPLACE GO";
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
This is going to work specifically for the problem you posted. Be sure to set all the parameters of your database server on the connection string, it seems from the comments on your question that you are having communication issues. You have to solve that problems before you do anything. Some tips for that:
Be sure you set all the parameters on connection string the right way
Try to connect using another tool like ODBC so you can test all parameters
Check out SQL Network settings to see if TCP/IP is enabled

Unable to connect to any of the specified MySQL hosts

I know that it is an easy problem but I can't find the error. I want to save data in my database. I create a database named "Examen" with Microsoft SQL Server 2008 then in my app in visual studio I make the connection string like this :
string connectionstring = #"Data Source=.\sqlexpress;Initial Catalog=Examen;Integrated Security=True";
Then I use this code to insert data into a "Test" table:
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into Examen.Test (nom,prenom) values (" + txbnom.Text + "," + txbprenom.Text + ") ";
cmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception)
{
throw;
}
finally
{
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
}
When running this code i had an error when openning the connection
Unable to connect to any of the specified MySQL hosts.
You are mixing MySQL and MSSQL.
Are you sure you want to connect to a MySQL server? Use http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx if you would like to connect to MSSQL.
Also you should make yourself familiar with SQL injection

How I create a SQL Server Compact 3.5 .sdf file and connect to it?

I have created a SQL Server Compact Database (.sdf file) and I want to be connected to it for do some insert , delete ... .
This is my creation code for it:
if (File.Exists(dbfilename))
File.Delete(dbfilename);
string connectionString = "Data Source=" + dbfilename + """;
SqlCeEngine engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
engine.Dispose();
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(connectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE Contacts (ID uniqueidentifire, Address ntext)";
cmd.ExecuteNonQuery();
}
catch { }
finally
{
conn.Close();
}
Is it true?
How can I connect to it?
That connection string is broken.
"
is not a valid entity where you are trying to use it. Fix your connection string.
Also, you will need to associate the command with the connection, either in the constructor or after the fact.
Please read through an example such as this one, which was the first google result for "connect sql compact example c#":

Categories

Resources