SQL connection string is not recognised and throws and exception in C# - c#

CONTEXT: I am writing a WPF app. It works with a SQL Server database in which I put some data, concretely the strings Titulo and Descripcion, the int XP and the string fotoMision. When I click a button the program is supposed to save this data in the database.
PROBLEM: when I click the button it throws me an exception in string connection's line showing that the object is not instanced. If I put these first lines right below the InitializeComponent(); line the second one doesn't recognise the miConexion string. Why does that happen and how can I fix it?
CODE:
static string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
SqlConnection miConexionSql = new SqlConnection(miConexion);
private void Button_Click(object sender, EventArgs e)
{
string consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
SqlCommand miSqlCommand = new SqlCommand(consulta, miConexionSql);
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}

Connections are meant to be short-lived, i.e. you should create one when the button is clicked and then dispose it right after you have executed the query. Using a using statement implicitly disposes the IDisposable:
private void Button_Click(object sender, EventArgs e)
{
const string Consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
using (SqlConnection miConexionSql = new SqlConnection(miConexion))
using (SqlCommand miSqlCommand = new SqlCommand(Consulta, miConexionSql))
{
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
}

The format of your connection string for a SQL Server Database should be like so:
"Data Source=DNS_or_IP_Address;Initial Catalog=DatabaseName;User Id=MyUser;Password=MyPassword"
Connection Strings and Examples for various databases

put connectionstring on form_load event

Related

How to get call trigger on c# Method using store procedure when i update table data without using sqldependency

i want call a C# method when i update table data or delete table data on every way like sql newquery 'Delete top(1) FROM [dbo].[Leaves]' like this and call c# method using store procedure. i perform it on sql dependencey but i don't need this i perform it using store procedure. you can see my code of sqldependecey. but i want another way to call this method using store procedure.
public class NotificationEvent
{
private delegate void RateChangeNotification(DataTable table);
private SqlDependency dependency;
string ConnectionString = #"Data Source=.;Initial Catalog=Message;Integrated Security=True";
string UserName = Environment.UserName;
public void RegisterForNotification()
{
var connectionString = ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var queryString = "SELECT [ID] FROM [dbo].[Leaves]";
using (var oCommand = new SqlCommand(queryString, connection))
{
// Starting the listener infrastructure...
SqlDependency.Start(connectionString);
var oDependency = new SqlDependency(oCommand);
oDependency.OnChange += OnNotificationChange;
// NOTE: You have to execute the command, or the notification will never fire.
oCommand.ExecuteReader();
}
}
}
private void OnNotificationChange(object sender, SqlNotificationEventArgs e)
{
Console.WriteLine("Notification Info: " + e.Info);
//Re-register the SqlDependency.
//var oDependency = new SqlDependency();
//oDependency.OnChange += OnNotificationChange;
RegisterForNotification();
}
}
#Umar Asif If the problem you face is totally regarding DB-to-DB communication, I would recommend a concept called "Merge Replication" in SQL Server (using Publisher-Subscriber(s)) design between DBs:
https://learn.microsoft.com/en-us/sql/relational-databases/replication/merge/merge-replication?view=sql-server-2017
Otherwise, if your problem requires a solution ONLY through a call to C# method, please refer:
How to call C# function in stored procedure

SqlDependency.OnChange fires on one database but not another on the same server

I'm trying to make a C# Forms program that views data from a database. It needs to request data on startup, cache it, then update it if the DB is updated. I'm trying to do it using SqlDependency. Here's the code:
private const string connectionString = "Data Source=DESKTOP-VT1F04F\\MSSQLSERVER14;Initial Catalog=test1;Trusted_Connection=True";
private void button1_Click(object sender, EventArgs e)
{
SqlDependency.Stop(connectionString);
SqlDependency.Start(connectionString);
ExecuteWatchingQuery();
}
private void ExecuteWatchingQuery()
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var command = new SqlCommand("select nbase, name from dbo.filial", connection);
var sqlDependency = new SqlDependency(command);
sqlDependency.OnChange += new OnChangeEventHandler(OnDatabaseChange);
command.ExecuteReader();
}
}
private void OnDatabaseChange(object sender, SqlNotificationEventArgs args)
{
//MessageBox.Show("?");
SqlNotificationInfo info = args.Info;
if (SqlNotificationInfo.Insert.Equals(info)
|| SqlNotificationInfo.Update.Equals(info)
|| SqlNotificationInfo.Delete.Equals(info))
{
MessageBox.Show("!");
//todo
}
ExecuteWatchingQuery();
}
It doesn't do anything. ExecuteWatchingQuery competes fully, but OnDatabaseChange never fires. However, if I replace database test1 with a freshly created database watcher_test with a freshly created table, it works as intended. I have tried the following SQL commands:
alter database test1 set enable_broker
CREATE QUEUE ContactChangeMessages;
CREATE SERVICE ContactChangeNotifications ON QUEUE ContactChangeMessages
Both databases have the same owner (as select name, suser_sname(owner_sid) from sys.databases shows), same permissions, they're on the same server, and I can't see any difference between them, in settings, or anywhere else. The program isn't able to access any table in the first database, but is able to access a copy of a table done with insert into from the first into the second table. The program behaves identically on a different computer that uses the same database restored from a backup.

Syntax of SQL Server database connection string in c#

I am beginner at SQL and thank you for your attention. I've created a database (by using "Add new Item" from "Project" menu and adding a "Service Based Database") in Visual Studio 2015 and now I want to connect to it and read or write data on it.
But I don't know how to connect to it by code.
I use the string showed in the connection string when I click on the database in server explorer.
That is here:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf";Integrated Security=True
But as you know, it cannot be used when I copy and paste it to a string thah can be used in new sqlConnection(connection string), because this string has '\' or ' " '
What's the right string for me to connect to this local database?
Now this is my code but it is not useful:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True");
con.Open();
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
SqlCommand cmd = new SqlCommand(t, con);
cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True"))
{
con.Open();
string t = "SELECT * From Table";
SqlCommand cmd = new SqlCommand(t, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader["Id"].ToString() + reader["name"].ToString());
}
con.Close();
}
}
Thank you for your help
Update: I get another errors in writing and reading table
I think I've connected to my database after using your help. and now I have another error in reading the table. this error points to
SqlDataReader reader = cmd.ExecuteReader();
in my code and says:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
and an error in writing on table points to
cmd.ExecuteNonQuery();
in my code:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
My database has one table named Table that contains two columns: Id(int) and name(nchar10)
The code you're using to connect to your Sql db is .. well ... really old school. We just don't do it like that any more.
So - what can we do instead? Lets use a nice library called Dapper which makes 'talking' to a sql server really easy, simple and safer.
First, install the package Dapper from nuget:
Create a POCO which will represent the data that is returned from the DB.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Now update the form code as follows:
private const string _connectionString = #"Data Source = (LocalDB) <snipped..>";
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (Id,name) Values (34, 'John')";
int rowsInserted;
using (var db = new SqlConnection(_connectionString))
{
rowsInserted = db.Execute(query);
}
if (rowsInserted != 1)
{
// Log/Handle the fact that you failed to insert 1 record;
}
}
private void button2_Click(object sender, EventArgs e)
{
IList<Foo> foos;
using (var db = new SqlConnection(_connectionString))
{
const string query = "SELECT * FROM Table";
// This will always return a list. It's empty or has items in it.
foos = db.Query<Foo>(query).ToList();
}
foreach(var foo in foos)
{
MessageBox.Show($"{foo.Id} - {foo.Name}");
}
}
Is that much cleaner? Yep - I thought so.
Of course, I would never put database code behind a winform event but into a dedicated class, etc. But I guess you're just learning/playing around/experimenting :) :)
Also, I've not put error handling in there, to keep the example smallish.
Change:
string t = "SELECT * From Table";
to:
string t = "SELECT * From [Table]";
and:
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
to:
string t=#"INSERT INTO [Table] (Id,name) Values (34, 'John')";
See https://stackoverflow.com/a/695590/34092 and https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql .
my problem has been solved
at first for connection to database I typed an # before connection string and deleted the quotes inside the string as #juergen d said in comments
at second for solving the error in writing and reading the table I typed [ and ] before and after the "Table" as #mjwills said
also #Pure.Krome explained a more professional way to improve the code
thank you every body

Error when accessing database

I'm really new to using databases with Windows WPF applications and am getting an error message as follows -
Format of the initialization string does not conform to specification starting at index 0.
I am unsure as to why this error is occurring and was wondering if anyone could help solve it?
The code I've used to try and connect to the database:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DataSet dataset = new DataSet();
private void Item_List_Loaded(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"F:\VS Projects\POS applicarion\POS applicarion\Imes.sdf");
SqlDataAdapter adapt = new SqlDataAdapter(conn.CreateCommand());
adapt.SelectCommand.CommandText = "select * from item";
adapt.Fill(dataset);
PopulateListBox();
}
}
Thanks!
As the comment in your question, the connection string is wrong.
You must supply the SqlConnection's constructor parameter with the correct syntax of SQL Server connection string.
For example:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
Please visit http://www.connectionstrings.com/sql-server/ for more syntax samples of connection strings.

how to update data from table using C#.net

I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.
Let me show you how I've coded, the code I did in frmViewformList savechanges button is :
private void btnSaveChanges_Click(object sender, EventArgs e)
{
string sql;
string UserName;
UserName = txtUserName.Text; // saving data loaded on run time to UserName
sql = "";
sql += "UPDATE UserLogin";
sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
sql += "WHERE Name= " + //how to access data which was in text box right after loading + ""; //
}
I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...
This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well.
I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.
You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.
It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.
Here is an example you can reference:
public void DoWork()
{
// Build Query Use #Name Parameters instead of direct values to prevent SQL Injection
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE UserLogin");
sql.Append("SET Name = #UpdatedName");
sql.Append("WHERE Name = #Name");
// Create parameters with the value you want to pass to SQL
SqlParameter name = new SqlParameter("#Name", "whatEverOldNameWas");
SqlParameter updatedName = new SqlParameter("#UpdatedName", txtUserName.Text);
Update(sql.ToString(), new [] { name, updatedName });
}
private static readonly string connectionString = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public static int Update(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
}
You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...
This is probably best done using
string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);
Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.
At the top of your .cs file you should have.
using System.Data.SqlClient; // for sql server for other data bases you should use OleClient instead.
And inside your button click event you could put the following.
// to know how to get the right connection string please check this site: http://www.connectionstrings.com
string connString = "database connection string here";
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//insert text into db
string sql_insert = "INSERT INTO ....."; // Use parameters here.
SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
int rowsAffected = cmd_insert.ExecuteNonQuery();
}
Hopefully this is enough to get you started.

Categories

Resources