Friends need your help!
I'm doing game project as my qualification work in University. I do this in Unity3D.
As main part of my project I must use databases in my qualification work.
I have created database in SQL Server 2014 Express and trying to use this database in my Unity project. My code is below.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data.SqlClient;
public class GObj : MonoBehaviour {
public void WorkWithDatabase()
{
string connectionstring = #"Data Source=127.0.0.1;Initial Catalog=GameForDiplom;Integrated Security=True;";
SqlConnection Myconnection = new SqlConnection(connectionstring);
Myconnection.Open();
Debug.Log("OPEN SUCCESS!");
using (var cmd = Myconnection.CreateCommand())
{
cmd.CommandText = #"SELECT * FROM [User]";
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Debug.Log(rdr["IDuser"] + "\t" + rdr["Nickname"] + "\n");
}
}
}
Myconnection.Close();
Debug.Log("CLOSE SUCCESS!");
}
}
During connection to my database in game i receive this
ERROR:
SocketException: The connection is not established, since target machine actively refused the connection request.
Please, I would like to see working code in C# and your settings of SQL 2014 Express which you use. I tried to open TSP port 1433 but I receive this
ERROR:
NullReferenceException: Object reference not set to an instance of an object
Mono.Data.Tds.Protocol.TdsConnectionPool.GetConnection ()
Friends, i'm not pro programmers as you can see, but i'm trying to be better! Please, help!
Thank you for help, Friends!
Related
I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1)
I have enabled my IP address within Azure's Firewall rules.
I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.
However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The requested address is not valid in its context.)
The C# code;
using System;
using System.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
I've tried temporarily turning off the firewall on my PC, but that made no difference.
The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at.
I created one Azure SQL database and allowed my client IP like below :-
I created one .Net Console application and ran your code, I replaced
using System.Data.SqlClient
with
using Microsoft.Data.SqlClient
You can use any of the above packages.
Copied connection string from Azure Portal > Azure SQL server > Connection string refer below :-
C# Code:-
using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * FROM Products";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
Output :-
I tried to run the code with the connection string format you mentioned in the comments :-
Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And I was able to run the same code above and got the desired output:-
When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below :-
Verify if your connection string has any syntax missing and validate it from Azure Portal.
I ended up taking a copy of the project home and running it on my home PC, and it worked correctly and reliably (after telling Azure to allow that IP address as well)
It turned out the answer was embarrassingly obvious - in addition to the standard Windows 10 firewall, my work PC is running another virus protection/firewall software, and that also needed to be told to allow the app thru.
Definitely one to remember for next time... Although I am kind of intrigued that on two occasions (once mentioned above, once afterwards) out of a few hundred attempts the app did manage to get thru and connect.
Thank you everyone for your answers and help.
Is self signed certificate disrupting connection to mysql?
I already give action crud in data and grant access to administration.
but the connection still got error.
Unable to connect to any of the specified MySQL hosts
my team connection like this:
Catalog=devbaf;User Id=userclient;password=client123
connection code:
try
{
string constring = "SERVER=123.45.678.9;DATABASE=devbaf;User Id=backendsystem;PASSWORD=1q2w3e4r5t;";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM users"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvtest.DataSource = dt;
gvtest.DataBind();
}
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message.ToString());
}
explanation problem:
I make a database in local server, so my friend can access to it to insert data. but when he make a connection script it wont connect to my database but can connect to server. He already tries to move some file to the server and it works,but the connection to database wont connect. i don't have an experience for this coz im php programmer not c# programmer. hope my explanation is clear.
I have found your error message like trying to connect the host but in your connection string is missing the MySQL server name or host address. I hope if you add the MySQL hostname or server address to your connection. it will fix your issue.
you can try this
string connectionString ="SERVER=servername; DATABASE=databasename; User Id=userid; PASSWORD=password;";
I am converting a VB6 app to .NET
The VB6 app connects to a MS SQL Server fine and always has via an ADODB Connection. I set it up using a connection string.
The SQL Server is on the network, it is not on the local machine.
When I try to connect using the same connection string in .NET (VB or C#) I get a "timeout expired" error. I return to my VB6 app and it connects up just fine.
I am not able to amend the network set up as it is not my network.
The C# code I am using is below:
using System;
using System.Data;
using System.Data.SqlClient;
namespace CommandLineApp
{
public class ConnectionDemo
{
public static void Main(string [] args)
{
SqlConnection myConnection = new SqlConnection
(
#"Data Source=192.168.0.5;" +
"Initial Catalog=mydb;" +
"User Id=myid;" +
"Password=mypass;"
);
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I have tried all sorts of different things in the connection string including using the server name, using "tcp:,port".
Interestingly enough I am not able to ping the server on IPv6 ("ping -6 ")
I remind you that I am unable to make changes to the network as it is not mine however the VB6 code works just fine. Same connection string. So I don't see why I should have to alter the network.
Thanks in advance.
Try
OleDbConnection myConnection = new OleDbConnection("Provider=SQLOLEDB; " +
"Data Source=192.168.0.5; " +
"Initial Catalog=mydb; " +
"User Id=myid; " +
"Password=mypass; ");
stackoverflow community! Once more, I come here seeking for your help...
My problem is: I have made a c# application used to register accounts in a MySQL database hosted by Byethost (SecureSignup). The connection works, but not all the time, even though no conditions are changed.
One minute I can submit the query and PhpMyAdmin shows it as beeing written in the database, but a few minutes later, when I try the exact same thing, I get various timeout errors ranging from "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." to "Timeout IO Operation"... Here is my code, maybe having it could help you understand why it has such a strange behaviour from time to time, because I sure can't.
(I have granted my IP remote MySQL access from the cpanel, and the login data are 100% correct)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Main
{
public partial class Form1 : Form
{
string connString;
MySqlDataReader reader;
MySqlConnection conn;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "INSERT into users (Username,password) VALUES('" + usr.Text + "','" + pass.Text + "')";
conn.Open();
int timeoutvalue = conn.ConnectionTimeout;
command.ExecuteNonQuery();
MessageBox.Show(timeoutvalue.ToString()); //This was a curiousity, it displays 15
conn.Close();
}
}
}
You should use parameters to prevent SQL injection.
Also use the using statement to properly dispose your MySQL objects.
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
using (conn = new MySqlConnection(connString))
{
string query = "INSERT INTO users (Username, password) VALUES (#usr, #pass)";
// are you sure your column name is Username and not username ?
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(conn, query))
{
cmd.Parameters.AddWithValue("#usr", usr.Text);
cmd.Parameters.AddWithValue("#pass", pass.Text);
cmd.ExecuteNonQuery();
// No need to close your connection. The using statement will do that for you.
}
}
}
As for the connection problems, I think you should contact your host for answers. I use MySql all the time using C#, without any problems, so i think it's a problem with your hosting.
I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.