SQL connection string in web service c# - c#

Hi I'm having a problem finding the correct connection statement for my web-service to an sql-server database. I'm trying to retrieve data from my database to check a users login details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace BTC_Service
{
public class UseDatabase
{
SqlConnection sqlConn;
internal Boolean Connect()
{
try
{
sqlConn = new SqlConnection(#"Integrated Security=true; Initial Catalog=BTCFS_DataBase; Data Source=.\SQLEXPRESS;");
sqlConn.Open();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal void DisconnectDatabase()
{
sqlConn.Close();
}
internal Boolean ExecuteCommand(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
return true;
}
catch (SqlException ex)
{
return false;
}
}
internal SqlDataReader ExecuteQuery(String query)
{
try
{
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = query;
return cmd.ExecuteReader();
}
catch (SqlException ex)
{
return null;
}
}
}
}
The database is created with sql-server 2008 and the path for it is:
C:\BTCFS_DataBase\db_BTDC_data.mdf
and the log file
C:\BTCFS_DataBase\db_BTDC_log.ldf
There is no password for the database and the code is as follows:
USE master
GO
create database db_BTCFC
ON PRIMARY
(
NAME = 'db_BTCFC_Data',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_data.mdf',
SIZE = 5MB,
FILEGROWTH = 10%
)
LOG ON
(
NAME = 'db_BTFC_log',
FILENAME = 'c:\BTCFS_DataBase\db_BTDC_log.ldf',
SIZE = 5MB,
FILEGROWTH = 10%
)
GO
Is there any suggestion to what I am doing wrong?
Should I add the database to visual studio in a specific way?
Or am i creating my database in the wrong way?
Thank you in advance.

The fact that you are connected using Integrated Security, means that your local user account on Windows should be authenticated on the SQL server instance which is hosted locally on your machine (evident by the "." in the Data Source, which refers to your local machine). It might be that the setup of your SQL server instance doesn't accommodate windows authentication. Check that your configuration allows for "mixed mode" authentication, i.e. either Windows authentication or username/password authentication...

I found this statement to be more effective than the previous one:
sqlConn = new SqlConnection(#"Integrated Security=SSPI; Initial Catalog=BTCFS_DataBase; Data Source=localhost");
Thanks #Wolfish for the link.

Related

CLR Stored Procedure Unable to connect with SqlConnection Regular Connection

I tried to create a CLR stored procedure in VS2017 but encountering error "NOT Connected." while executing that stored procedure.
I need to connect to other database server to grab some data. Therefore I cannot use context=true in SqlConnection.
Stored procedure will be created in serverA
This stored procedure will query data from serverB
Data will be stored back to serverA.
Is there anything I need to do in order to have regular connection in CLR stored procedure?
Please advise. Thanks!
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void udp_CLR_GetData()
{
string ConnStr = "server=MyServer; database=MyDB; user id=accabc; password=abc123";
string sql = " select top 1 ID from [dbo].Table1 ";
SqlDataReader dr = null;
DataTable dt = new DataTable();
try
{
using (SqlConnection fcon = new SqlConnection(ConnStr))
{
if (fcon.State == ConnectionState.Open)
{
SqlContext.Pipe.Send("Connected.");
using (SqlCommand fcmd = new SqlCommand(sql, fcon))
{
SqlContext.Pipe.Send("Before executing reader...");
dr = fcmd.ExecuteReader();
SqlContext.Pipe.Send("After executing reader...");
SqlContext.Pipe.Send("Before send...");
SqlContext.Pipe.Send(dr);
SqlContext.Pipe.Send("After send...");
}
}
else
{
SqlContext.Pipe.Send("NOT Connected.");
}
}
}
catch(Exception ex)
{
SqlContext.Pipe.Send("Exception error (udp_CLR_GetData): " + ex.Message);
}
finally
{
if(dr != null && !dr.IsClosed)
{
dr.Close();
}
}
}
}
Creating a new instance of a SqlConnection in:
using (SqlConnection fcon = new SqlConnection(ConnStr))
does not create it in an "open" state. You need to actually open it for it to be "open". So, I would remove the if (fcon.State == ConnectionState.Open) and the associated else part of it. I would also remove the SqlContext.Pipe.Send("Connected."); line.
Then, just before the dr = fcmd.ExecuteReader(); line, add a line for:
fcon.Open();
This way you open the connection and immediately execute the command. No need to open the connection only to do other work getting the command ready.
For more info on working with SQLCLR in general, please visit: SQLCLR Info
Try defining the data source in the connection string instead of server
string ConnStr = "DataSource=MyServer;Initial Catalog=MyDB;User Id=accabc;Password=abc123";
other than that, make sure clr is enabled on the server:
https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/clr-integration-enabling?view=sql-server-ver15

Xamarin, MySQL exception: unable to connect to any specific host

I want to make an simple app that will get data out of remote database and show it on a screen, so first I made a simple console app to test connection and it all works. here's code :
static void Main(string[] args)
{
MySqlConnection con = new MySqlConnection("SERVER=85.10.205.173; PORT=3306; DATABASE=mybasework; UID=neawin; PWD=12345678; old guids=true; Connection Timeout=30;");
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM motto", con);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["motto"]);
}
}
}
}
catch(MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
con.Close();
}
}
But then when i tried to test connection on my phone it shows that it is unable to connect to the host, here's code:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using MySql.Data.MySqlClient;
using System.Data;
namespace App1
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
private TextView Textmotto;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Textmotto = FindViewById<TextView>(Resource.Id.textmotto);
MySqlConnection con = new MySqlConnection("SERVER=85.10.205.173; PORT=3306; DATABASE=mybasework; UID=neawin; PWD=12345678; old guids=true; Connection Timeout=30;");
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
Textmotto.Text = "Success";
}
}
catch (MySqlException ex)
{
Textmotto.Text = ex.ToString();
}
finally
{
con.Close();
}
}
}
}
I think i tried every variation of connectionstring I could, in first program I used mysql.data library and in phone app I used Xamarin.Mysql Nuget Package if that makes any difference. Sorry for english and poor formatting, my first post.
Its probably a network issue. But please, don't do this. In order to directly connect to a DB, you need to put the password to your db in plain text in your app (even if you encrypt it, the key is in your app). This is totally insecure, and any script kiddie can own your database. If you need data from a database, write a webservice and have the webservice access the db, so you never need to have the authentication information leave your own servers.
thanks for help, I resolved the issue by adding INTERNET permission in my manifest as suggested by Vladyslav.

Doesnt execute my MySql Query

i have a little problem with my C# code(im normally a c++ dev so i just know most of the basics of c#)
I wanted to write a class to execute a SQL query using that programm but atm it does nothing and i donĀ“t get any error from it.
The MySqlConnectionHandler Class which i wrote:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace WS_Studio_tool
{
class MySqlConnectionHandler
{
private MySqlConnection connection;
private string ConnectionString;
public MySqlConnectionHandler()
{
try
{
ConnectionString = "SERVER=localhost;" +
"DATABASE=ws_creator_beta;" +
"UID=root;" +
"PASSWORD=AF362GL!";
connection = new MySqlConnection(ConnectionString);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "MySql Fehler!");
}
}
public bool InsertRow(string SQL_Query)
{
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = SQL_Query;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "MySql Fehler!");
}
return true;
}
}
}
My Function Call(I played a lot with it so it could contain things that are not necessary):
string newquery = QueryTextBox1.ToString();
MySqlConnectionHandler SqlHandler = new MySqlConnectionHandler();
SqlHandler.InsertRow(newquery);
And my MySql Query:
INSERT INTO user_data (username,passwd) VALUES ('asdf', 'asdf');
It would be very nice if somebody could take a quick look at it, maybe you are able to find the error..
You're not telling the command to execute: also, you need to explicitly open the connection before using it, so add these lines to InsertRow:
connection.Open();
command.ExecuteNonQuery();
I'd also suggest disposing of the connection once you're done with it - either by implementing IDisposable on the MySqlConnectionHandler class, or - easier - just create a connection within a using block when executing the query:
using (var connection = new new MySqlConnection(ConnectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = SQL_Query;
connection.Open();
command.ExecuteNonQuery();
}
}
You did not call command.Execute, so your SQL never gets executed.

How do I create a MySql database connection that returns results to a text file?

I want to write a MySql statement that will connect to the database, select a column from the table, then output that data to a text file to a specific location on my computer. I have searched the internet for a couple days now and don't seem to find the answer I am looking for. I am fairly new to c#, MySql, and Visual Studio. I am just trying to learn how to write the correct statements and get the desired result. Any help would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Windows.Forms;
using System.IO;
namespace NewPractice
{
public class Connect
{
static void Main()
{
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(results);
conn.Open();
//Console.WriteLine(
File.WriteAllLines(
#"C:\Documents and Settings\anyone\My Documents\Tests\testoutput.txt",
results.ToArray());
}
catch (MySqlException ex)
{
Console.WriteLine("Error: (0)", ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
You're writing the contents of the result string to the file, not the data you're attempting to select. You need to run a sql command and get a SqlDataReader object to write your data to the file.
string results = #"server=111.111.11.111; userid=anyone;
password=anypassword; database=anydatabase";
MySqlConnection connection = new MySqlConnection(results);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "select * from mycustomers";
connection.Open();
reader = command.ExecuteReader();
using(var sw = new StreamWriter("C:\MyPath\MyFile.txt"))
{
while (reader.Read())
{
var row = (IDataRecord)reader;
sw.WriteLine(row["myColumn"]);
}
}
connection.Close();
If the database is on your local machine you can use 'select .. into outfile'. http://dev.mysql.com/doc/refman/5.1/en/select-into.html. This will write to a folder on the server so it's not v useful if it's a different machine and you can't copy from there.
There are plenty of tutorials out there for accessing MySQL from .NET.
This is one: http://zetcode.com/db/mysqlcsharptutorial/
In any language, there are a few simple steps to read from a database:
1. connect to the database.
2. execute a query
3. iterate through the results of the query
4. close the connection.
What you are doing in your code is connecting to the database and then trying to write the connection information to a file.

How to connect with a database on Access inside a intranet

I have made connection with sql server but i have never done a connection with access and
now this isn't in the computer local, if not it is going to be in a server
users are going to full the form with their information, but the database will be in another computer, how is the connection class to be? and I have never worked in access
how do i for Add, Edit, delete, and queries?
in sql server it was so easy
it was my class connection in sql and i call it since form or another class called DAO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace Proyecto1._0.Conexiones
{
class Conexion
{
public SqlConnection conectar()
{
return new SqlConnection(#"data source=.; integrated security=true; initial catalog=dbmeridajoven;");
}
public bool ejecutarConsulta(string consulta)
{
try
{
SqlCommand comando = new SqlCommand(consulta, this.conectar());
comando.Connection.Open();
comando.ExecuteNonQuery();
comando.Connection.Close();
return true;
}
catch
{
MessageBox.Show("Consulta mal formada");
return false;
}
}
public DataTable regresarTabla(string consulta)
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(consulta, this.conectar());
DataTable tabla = new DataTable("consulta");
adapter.Fill(tabla);
return tabla;
}
catch
{
MessageBox.Show("Consulta mal formada ");
return new DataTable();
}
}
}
}
I repeat now is with access and it is for intranet (in another computer is the server)
ConnectionStrings.com is a great resource for figuring out how to create a connection string for a variety of database engines. Here's one example of an Access connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;
Once you generate a connection string, you'll notice that the file path is included in the string; to share the database among mulitple clients, you'll need to put the database file on a network share or drive. For example, your file path could be something like "\\dbserver\databases\mydb.mdb."

Categories