Can't connect with SqlConnection [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
What is wrong with my code or connection string? Always can't connect to database.
string c = null;
SqlConnection sql;
c = "Data Source=127.0.0.1, 3306;Network Library=DBMSSOCN;Initial Catalog=testowa;User ID=kuba;Password=123";
sql = new SqlConnection(c);
try
{
sql.Open();
MessageBox.Show("Connected!");
sql.Close();
}
catch (Exception ex)
{
MessageBox.Show("not connected :(");
}

You are trying to connect to a MySql database not to a Sql Server one. These are two different products and require different connection strings, different classes and different ADO.NET Providers.
First, download and install the MySql Connector/NET from here
Second, go to your project references and add a reference to
MySql.Data.dll
Third, remove the using System.Data.SqlClient and add using MySql.Data.MySqlClient in every source file where you have the database code
Fourth, change your code to use the appropriate classes like
MySqlConnection, MySqlCommand, MySqlDataReader, etc...
Finally, use a proper connection string for MySql
using(MySqlConnection sql = #"Data Source=127.0.0.1;
Database==testowa;uid=kuba;Pwd=123;Port=3306"))
{
try
{
sql.Open();
MessageBox.Show("Connected!");
}
catch (Exception ex)
{
MessageBox.Show("not connected :(" + ex.Message);
}
}

Related

Is it wrong to not use Models on ASP NET Core Razor Pages? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've been working with ASP NET Web Forms for a while and we have been communicating with the database like this
using (MySqlConnection con = new MySqlConnection(conexao))
{
try
{
string sql = string.Format("SELECT ID_Cliente, Nome, Cnpj, FL_Filial FROM cadastro_cliente WHERE ID_Cliente = {0}", ID_Cliente);
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader = null;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
flf = Convert.ToInt32(reader["FL_Filial"].ToString());
}
}
catch (MySqlException ex)
{
string vLog = "#Erro#: " + ex.Message;
EscreveLog(vLog);
}
finally
{
con.Close();
con.Dispose();
}
}
My question is, is it right if I use the same way to communicate with the database? Like not using Models or anything. Reminding that I'm new to ASP NET Razor Pages.
You could program anything, Visual Studio allows you to do anything in Controllers. But.. see comments of Franz ! they are relevant. To avoid the pitfalls Franz has pointed out, I would recommend using Entity Framework instead of directly using SQL. That would introduce models (DBContext) anyway.
ASP.NET was designed for MVVM and the only difference with ASP.NET Core is the implementation. I would say the answer to this question is yes, skipping the model is wrong.. unless you do not want to adhere to MVVM programming methods.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

C# - How can I do MS SQL Server Connection? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I started programming recently and at the moment I am developing a program with SQL Server 2019 and Visual Studio 2019 in C# that performs simple functions for inserting, deleting and displaying data but I cannot understand how to set up the initial connection with SQL Server. I already connected the Database from Tools->Connect to Database... and the connection test was successful, but now I don't know how to set the connection via SQL Server Authentication by code.
It all depends how you want create the connection really..
At the very top of your form be sure to include
using System.Data.SqlClient;
using System.Configuration;
Depending on how you want to create the connection on whatever button trigger or page load... this scenario would be for you to get specific fields of a query:
string qString = "SELECT value1,value2,value3 FROM database WHERE value 1 = 'hello world'";
using(SqlConnection connection0 = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNECTION_STRING_NAME_HERE"].ToString()))
using(SqlCommand command0 = connection0.CreateCommand())
{
command0.CommandText = qString;
connection0.Open();
using (SqlDataReader reader = command0.ExecuteReader())
{
while (reader.Read())
{
value1string = reader["value1"].ToString();
value2string = reader["value2"].ToString();
value3string = reader["value3"].ToString();
}
}
connection0.Close();
}
Be sure to add the connection string to the app.config file:
<connectionStrings>
<add name="CONNECTION_STRING_NAME_HERE"
connectionString="Data Source=SERVERINSTANCENAME;Initial Catalog=YOUR_DATABASE_NAME;User ID=DATABASE_USERNAME;Password=DATABASE_USER_PASSWORD;" />
</connectionStrings>

How to save and store the data in Azure SQL database using C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am seeking help in storing and saving data in Azure SQL Database. Could anyone please help me with how I can code in C# or the libraries required to do the same
Update:
You can also use the following code, it's a simple .NET framework console project and all the needed assembly is added by default:
using System;
using System.Data.SqlClient;
namespace ConsoleApp13
{
class Program
{
static void Main(string[] args)
{
//define the connection string of azure database.
var cnString = "Server=tcp:xxx.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxx;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
//define the insert sql command, here I insert data into the student table in azure db.
string cmdText = #"insert into student
(name,age)
values(#name, #age)";
using (SqlConnection con = new SqlConnection(cnString))
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", "yang1");
cmd.Parameters.AddWithValue("#age", 20);
cmd.ExecuteNonQuery();
con.Close();
}
Console.WriteLine("completed***");
Console.ReadLine();
}
}
}
It can insert data successfully into azure database at my side. The screenshot as below:
The official doc provides all the CURD operations. Follow this doc to fetch azure sql database connection string, and set firewall.
The needed assembly is System.Data.dll, which should be added by default when create a project in visual studio.
The sample code is here. For save data, you can see this method static string Build_3_Tsql_Inserts() in this section Methods that return T-SQL statements.
I would request you to start with the Documentation and try the course Provision an Azure SQL database to store application data
Try working threw these.
A Example
Another Example

C# Connecting with remote mysql database, getting the error “Unable to connect to any of the specified MySQL hosts” [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I was looking on many posts about this problem but not found an answer.
I try to connect to mysql DB that exist on some server, I use with the following code from https://www.connectionstrings.com/sql-server-2014/ and https://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
private string server = "xx.xxx.xxx.xx";
private string database = "testDB";
private string username = user;
private string password = password;
string connectionString;
connectionString = string.Format("Server={0},3306; Database=
{1}; User Id={2}; password={3};", server, database, username,
password);
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
}
catch (MySqlException ex)
{
return false;
}
I install MySql.Data.dll from nuget console and open the port 3306(tcp) in the server.
When I try to open connection it gives me an error "Unable to connect to any of the specified MySQL hosts".
Someone has an idea why?
Thanks
Your connection string is not formatted correctly.
By separating entries with commas, you telling that there are multiple servers, which obviously is not the case. If you need to specify the port, try with:
connectionString = string.Format("Server={0}; Port=3306; Database=
{1}; Uid={2}; Pwd={3};", server, database, username,
password);
But it is not necessary as 3306 is the default port on which MySQL server accepts connections.
Here you can find more examples.
Your connection string should actually be fine.
Your problem is MySqlConnection. You have a MS SQL Server, not MySQL.
You should be using SqlConnection from namespace System.Data.SqlClient instead.
Your port probably isn't right, since it is the default MySQL-Port. Just try to leave out the port, then it will try to use the default port for MS SQL Server.

How do I send strings of data to a SQL query? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have created a simple Username and Password login form in visual studio using c# which works great I then coded it so that whatever Username and Password was entered into the two textboxes was saved as a string... Now I want to pass those strings as parameters and store them into an SQL query... Any idea how I would go about doing this?
I would highly recommend NOT to store passwords as plain text. Instead look into hashed password methods.
Firstly you will need to specify a connection string. This can be done in the config file as:
<connectionStrings>
<add name="myConnectionString" connectionString="server=ServerAddress;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Now you want to read the connection string from your config file and you can do that in your C# code as:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I'm assuming you'll be inserting records. If you are going to update records, then you will need to change the query. For inserting records:
string myQuery = "INSERT INTO MyTable (UserNameColumn,PasswordColumn) VALUES (#UserName, #Password)";
Finally to execute the query and pass our parameters we can do
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(myQuery, connection))
{
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = UserNameTextBox.Text;
cmd.Parameters.Add("#Password", SqlDbType.NVarChar).Value = PasswordTextBox.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
}
Dont forget to include the namespace using System.Configuration;

Categories

Resources