Getting Error while connecting to DB using c# - c#

Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)

When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}

In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.

Related

How to resolve "Ensure SQL Server Browser is running" , when it is

I'm creating an Android App using Xamarin Forms in Visual Studio 2017. Since this includes storing data, I'm using SQL Server 2017 to accomplish this. When I run my code, and debug the line "conn.Open()", I get an error stating that I should ensure that SQL Server Browser is running. However, when I check SQL Configuration Manager, it is running.
Some things I've tried
- Making sure that the connection string in SQL Server matches the connection string in my code
- I've tried changing what the SQL Server Browser is logged into (Whether it's local system, local service, etc.)
- I've tried several different methods of implementing an insert statement in my code
public class ConnectionManager
{
public static SqlConnection NewCon;
public static string ConStr = #"Data Source=DESKTOP-V83O00S\SQLEXPRESS;Initial Catalog=ResourceSharing;Integrated Security=True";
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection(ConStr);
return NewCon;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
SqlConnection conn;
conn = ConnectionManager.GetConnection();
conn.Open();
string cmdString = "INSERT into Login values(#username,#password)";
SqlCommand sqlCommand = new SqlCommand(cmdString, conn);
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#username", SqlDbType.Text).Value = "josh123";
sqlCommand.Parameters.Add("#password", SqlDbType.Text).Value = "pwd321";
sqlCommand.ExecuteNonQuery();
conn.Close();
}
Expected Result: 1 record in my Login table
Actual Result: Error asking me to ensure SQL Server Browser is running.
Any feedback or suggestions on either how to fix this problem or what alternative route I can take that would work?

How do I connect to a Local MSSQL Database

EDIT: I've just tested it in ASP.NET and it works perfectly fine. So no issue with the connection string or anything. Guess Unity doesn't like this method? Maybe there's some more DLL's I need to copy? Any ideas?
So I'm making a game in Unity and I'm trying to use the System.Data.SqlClient library to connect to some stored procedures I have made for things such as registering a user.
I have copied the System.Data.dll from "C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity" and that has all worked fine.
I'm currently using this connection string, which works fine on an ASP.NET application but just using a different mdf:
private string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf';Integrated Security = True";
The problem occurs when running this code:
using System.Data.SqlClient;
using System.IO;
public void Login()
{
Crypto crypto = new Crypto();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
} catch (Exception e)
{
Debug.Log(e);
}
SqlCommand command = new SqlCommand("USERS_LOGIN_USER", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Username", usernameInputField.text));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (crypto.EncryptString(passwordInputField.text) == reader["password"].ToString())
{
UserAccountManager.instance.userInfo = FetchUserInfo((int)reader["id"]);
}
}
}
}
The problem happens on the line "conn.Open()", where Unity gives me the error:
System.Net.Sockets.SocketException: No such host is known.
Furthermore, without the try catch, the error occurs where I create a new SqlDataReader, where I get this issue:
InvalidOperationException: ExecuteReader requires an open connection to continue. This connection is closed.
I understand that this is an issue with the connection, in that it's not running or the connection isn't working properly, however I can't seem to find a solution and I have a sneaky suspicion that it's something to do with Unity not supporting this library.
Some more clarification just before I end off:
The user enters their credentials into the "usernameInputField" and "passwordInputField"
The user presses Login, which runs the "Login" method shown above
The error occurs.
If any more information is required please leave a comment.
Thanks!
What is the scope of connectionString? Do you need to pass the connectionString to the Login() function?
public void Login(string connectionString)
I am a DBA, not a .Net developer, so forgive me if my questions are too basic or if my .Net syntax is wrong.
You can try this
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog ='C:\USERS\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf'; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"
SqlConnection con = new SqlConnection();
if (con.State==ConnectionState.Open)
{
con.Close();
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}
else
{
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

ASP .net C# SqlConnection Error

I have a window hosting in 1and1.com. I try to connect the database with following code, but I get the error message. You can view error message here http://www.s499993321.onlinehome.us/Default.aspx
Does any one know happen? How to connect the database?
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection("Server=localhost; Database=db500148144; User Id=dbo500148144; Password=12345abc"))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM people", cn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString());
}
// Response.Write("How");
}
If SQL server is on the same machine use
SqlConnection cn = new SqlConnection(#"Server=.\MSSQLSERVER2012; Database=db500148144; User Id=dbo500148144; Password=12345abc")
MSSQLSERVER2012 is the instance name. One way to find out the name is by opening services.msc and checking the name of the sql server service running on your machine. for me it was
"SQL server(MSSQLSERVER2012)"
There is issue in your web.config file, Remove CustomeErrro tag from web.config , and try.

connect to MySQL webserver with C#

I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';

Categories

Resources