Insert textbox value to sqlserver table - c#

I have a problem with inserting a TextBox value into a SqlServer table. I wrote that code, but when I run the form it raises a runtime error: "a network-related or instance-specific error occurred while establishing a connection to sql server". Thanks in advance.
public partial class Add_Client : Form
{
SqlConnection clientConnection;
string connString;
SqlCommand insertCommand;
public Add_Client()
{
InitializeComponent();
connString = "Data Source=.//INSTANCE2;Initial Catalog=Clients;Integrated Security=True";
clientConnection = new SqlConnection();
clientConnection.ConnectionString = connString;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand insertCommand = new SqlCommand();
insertCommand.Connection = clientConnection;
insertCommand.CommandText = "INSERT INTO Client_Info values(#Client_Name,#AutorizationNo,#IssueType,#Status)";
insertCommand.Parameters.Add("#Client_Name",SqlDbType.NVarChar,60).Value=txt_Name.Text;
insertCommand.Parameters.Add("#AutorizationNo", SqlDbType.Int, 60).Value =txt_Auth.Text.ToString();
insertCommand.Parameters.Add("#Issue", SqlDbType.Text, 200).Value =txt_Iss.Text;
insertCommand.Parameters.Add("#Status", SqlDbType.TexT, 15).Value=txt_sta.TexT;
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (clientConnection != null)
{
clientConnection.Close();
}
}
}
}

the .// in the host name in your connection string shouldn't be there. i wouldn't expect it to work. you should just have the machine name itself there.

You need to check your connecting string, u may find it usefull:
http://www.connectionstrings.com/
If you are sure about the connection string then please check your database status.

The parameter names in SQL should not contain blanks. I you want to use blanks you have to enclose the parameter name in square brackets.

Is your connection string correct? That basically means it couldn't connect to the server.
Also, just a tip - I wouldn't do this:
insertCommand.Parameters.Add("#Autorization No", SqlDbType.Int, 60).Value =txt_Auth.Text.ToString();
...
Its just asking for trouble. Instead copy it, sanitize it and make sure that it won't cause an exception.

Related

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.
When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.
I have also noticed that my database connection often disconnects unless I refresh, is this common?
namespace AttendanceTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void signInButton_Click(object sender, EventArgs e)
{
string connectionString = null;
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#Student_Name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#Student_ID", studentIDTextBox.Text);
cmd.Parameters.AddWithValue("#Class", classDropDown.Text);
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Your sign in has been recorded successfully!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open attendance tracker for updating.");
}
}
When using Parameter objects, you should ensure that the variable names are consistent.
Please modify your code as follows
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("#studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("#class", classDropDown.Text); // Modified to "class"

Adding records to MS Access database through C#

I am attempting to add items to an Access database in C#. I have code that seems to work (I can open and close a database), but the button click event produces errors. I have been searching on Google for the whole afternoon but no joy. My code is:
private void button26_Click(object sender, EventArgs e)
{ //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value', 'Default','Type') VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}
And the error I get is:
Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\Somepath\Form1.cs:line 49
Clearly something wrong with the connection string, and that it's not SQL-injection proof either.
The problem is well known. A command need to know the connection to use to execute the command text. However you have other problems in your code.
Connection objects (like commands) should not be global, but created when they are needed and destroyed after. The using statement is very usefull here because you don't have to explicitly close and destroy these objects and you will never have resource leaks when an exception occurs.
Second, when you use field names that are also reserved keywords in your database you should enclose these name in some kind of escape characters. These characters for Access are the open/close brackets not the single quote.
private void button26_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"INSERT INTO Main
([Prop], [Value], [Default],[Type])
VALUES('one', 'Kelly', 'Jill','one')";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
connection.Open();
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
}
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
}
}
Finally I don't know if your fields are of text type. You pass literal texts so they should be of text type and remember to use parameters when you switch this simple code to your actual values.
Assign Connection property as below line.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
Per #Steve's comment, there is no connection associated with the command when you just instantiate it like that. You need to either set the Connection property of the command or better yet use connection.CreateCommand() to create the command in the first place in which case it will already be associated with the connection (cleaner).

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

Local DB: “A network-related or instance-specific error occurred while establishing a connection to SQL Server.”

I have already checked other topics regarding the matter and tried some of the standard solutions but nothing seems to work. My DB is local and I'm trying to connect, it is already created and saved in the folder Helpers with the name of localDB.mdf
My code is:
public static List<ChatMessages> GetFromDatabase(string query)
{
List<ChatMessages> ImportedFiles = new List<ChatMessages>();
string sql = #"Data Source=|DataDirectory|\Helpers\localDB;AttachDbFilename=\Helpers\localDB.mdf;Integrated Security=True";
SqlConnection connection = new SqlConnection(sql);
try
{
connection.Open();
var check = connection.State;
SqlCommand cmd = new SqlCommand(query, connection);
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//stuff
}
connection.Close();
}
catch (Exception e) { MessageBox.Show("error: " + e); }
var x = ImportedFiles;
return ImportedFiles;
}
Thanks for your time,
Best regards
Already found an answer. After attempting a lot of hypothesis like the ones suggested by #Win I found the answer. So:
Project > Add New Data Source > Choose the local DB
And the connection string suggested was:
#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\localDB.mdf; Integrated Security = True"
The difference is in the MSSQLLocalDB and in the use of the environment variable.

C# Oracle connection string for DataGrid

When I import Dataset to application in connnection string I choose "No exclude information from connection string. I will set this information in my aplication".
Now when I compile the form there is nothing to see in the DataGrid, where I must place connection in my application to connet ?
Now I have:
public Form1()
{
InitializeComponent();
using (OracleConnection con = new OracleConnection("Data Source=localhost;Persist Security Info=True;User ID=martynas;Password=xxxxxxx;Unicode=True"))
{
try
{
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This conection is open, but DataGridView still does not show any records. I think that maybe I place connection in wrong method ?
You are not connecting your OracleCommand to anything. You create it but when it goes out of scope, it ceases to exists.

Categories

Resources