Error in setting up the connection between SQL Server and C# - c#

What is wrong with my code? When Im setting up the connection between sql server management studio and c#, it gives me this error " ExecuteNonQuery: Connection property has not been initialized."
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString= "Database= hotel; server= Sherissa\SQLEXPRESS";
con.Open();
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)");
cmd.Parameters.AddWithValue("#TransactionId",textBox1.Text);
cmd.Parameters.AddWithValue("#GuestName", textBox2.Text);
cmd.Parameters.AddWithValue("#RoomType", textBox3.Text);
cmd.Parameters.AddWithValue("#RoomNo", textBox4.Text);
cmd.Parameters.AddWithValue("#ReservationDate", textBox5.Text);
cmd.Parameters.AddWithValue("#CheckInDate", textBox6.Text);
cmd.Parameters.AddWithValue("#CheckOutDate", textBox7.Text);
cmd.Parameters.AddWithValue("#NoOfDays", textBox8.Text);
cmd.Parameters.AddWithValue("#NoOfAdults", textBox9.Text);
cmd.Parameters.AddWithValue("#NoOfChildren", textBox10.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}

I see several errors here.
The first error is the substance of your question. To solve that issue, you need to associate your command with a particular connection. Remember, you might be connected to several different databases at the same time. A command needs to know which connection to use.
The next error is that your Sql syntax is wrong. You are missing the required VALUES keyword.
Another problem is that you don't close the connection correctly. If an exception is thrown, the code will never make it to the con.Close(); line. If this happens often enough you will lock yourself out of your database.
Finally, a nitpick. I'm not a fan of the .AddWithValue() method, because it forces .Net to try to guess the sql datatype you're using. Sometimes it guesses wrong, and when it does the performance implications can be severe, because it can break index use on the database.
Here is code that solves all four issues:
private void button1_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection("Database= hotel; server= roger\SQLEXPRESS"))
using (var cmd = new SqlCommand("insert into CheckIn VALUES (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con))
{
cmd.Parameters.Add("#TransactionId", SqlDbType.Int).Value = int.Parse(textBox1.Text);
cmd.Parameters.Add("#GuestName", SqlDbType.NVarChar, 50).Value = textBox2.Text;
cmd.Parameters.Add("#RoomType", SqlDbType.NVarChar, 10).Value = textBox3.Text;
cmd.Parameters.Add("#RoomNo", SqlDbType.NChar, 4).Value = textBox4.Text;
cmd.Parameters.Add("#ReservationDate", SqlDbType.DateTime).Value = datetime.Parse(textBox5.Text);
cmd.Parameters.Add("#CheckInDate", SqlDbType.DateTime).Value = datetime.Parse(textBox6.Text);
cmd.Parameters.Add("#CheckOutDate", SqlDbType.DateTime).Value = datetime.Parse(textBox7.Text);
cmd.Parameters.Add("#NoOfDays", SqlDbType.Int).Value = int.Parse(textBox8.Text);
cmd.Parameters.Add("#NoOfAdults", SqlDbType.Int).Value = int.Parse(textBox9.Text);
cmd.Parameters.Add("#NoOfChildren", SqlDbType.Int).Value = int.Parse(textBox10.Text);
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}
Of course I had to guess at the datatypes to use, and in my own code I would also devote a little more effort to validating the inputs before trying to parse them.

SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)");`
This line should be typed as,
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)", con );

You need to assign the connection to your command:
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con);

Related

No mapping exists from object type System.Windows.Forms.DateTimePicker

When I press the register button, a MessageBox will show up and then this happens:
No mapping exists from object type System.Windows.Forms.DateTimePicker to a known managed provider native type.
How do I fix this?
SqlConnection sqlcon = new SqlConnection();
sqlcon.ConnectionString = #"Data Source=MYCOMPUTER-PC\SQLEXPRESS;Database=COMPPROG;User
Id=user;Password=password";
SqlCommand scmd = new SqlCommand("SELECT COUNT (*) as cnt from USERACCOUNT", sqlcon);
SqlCommand cmd = sqlcon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO USERACCOUNT
(FName,MName,Sname,TxtBirth,comboGender,textBox8,textBox1,textBox2)
VALUES(#FName,#MName,#Sname,#TxtBirth,#comboGender,#textBox8,#textBox1,#textBox2)";
cmd.Parameters.AddWithValue("#FName", FName.Text);
cmd.Parameters.AddWithValue("#MName", MName.Text);
cmd.Parameters.AddWithValue("#Sname", Sname.Text);
cmd.Parameters.AddWithValue("#TxtBirth", TxtBirth);
cmd.Parameters.AddWithValue("#textBox8", textBox8.Text);
cmd.Parameters.AddWithValue("#textBox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textBox2", textBox2.Text);
cmd.Parameters.AddWithValue("#comboGender", comboGender);
sqlcon.Open();
MessageBox.Show("Record added sucessfully!", "Registration Success!");
cmd.ExecuteNonQuery();
sqlcon.Close();
Like #gunr2171 said in comments problem is from this line so change it like this :
cmd.Parameters.AddWithValue("#TxtBirth", TxtBirth.Value);
This is value of TxtBirth for your query.
Edit :
And your error means you are passing the DatePicker itself and it can not be done.

Search sql server database server using Textbox and button in C#

So I am using MS visual studio to create an application in c# that will pull information from a sql server database.
I have created a textbox and a button to search my gridview. I am using a stored procedure that searched multiple rows to pull information from my Sql Database.
I am having trouble with my aspx.cs code. I have tried so many different ways to create a searchbox but haven't had any luck yet
Here is my code for my search button.
I am getting the error-
"Input string was not in a correct format."
this error is on the line cmd.ExecuteNonQuery();
Help is much appreciated, thank you.
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
string find = "sp_SrcProtocols";
SqlCommand cmd = new SqlCommand(find, con);
cmd.Parameters.Add("#ORAID", SqlDbType.Int).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#InvestLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
cmd.Parameters.Add("#ManagerLastName", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "ORAID");
da.Fill(ds, "InvestLastName");
da.Fill(ds, "ManagerLastName");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
By default, a SqlCommand expects a query, not a stored procedure's name. You have to set the command type before executing it.
cmd.CommandType = CommandType.StoredProcedure;
It seems, you are passing same text box value (TextBox_Srch.Text) to all 3 parameters. And first parameter #ORAID is expecting integer value and you might be passing text. So it's causing SQL server to raise below error.
Input string was not in a correct format.
This is what worked (and i changed my sql to just accept one parameter #search)
protected void Button_srch_invest1_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager.ConnectionStrings["ORAProjectConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "sp_SrcProtocols";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox_Srch.Text;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
}
}

Input on a stored sql procedure using C#

In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}

Can't connect to postrgres using Visual Studio with dotConnect

When I try to connect to DataBase, I get error: Key word doesn't support: Host.
int x = Int32.Parse(textBox1.Text);
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString =
Properties.Settings.Default.postgresConnectionString;
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getCount";
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("#k",
SqlDbType.Int);
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#Tovar", x));
con.Open();
cmd.ExecuteNonQuery();
string kolvo = cmd.Parameters["#k"].Value.ToString();
con.Close();
label1.Text = kolvo + " израсходован в количестве ";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Connection String:
User Id=postgres;Password=8loz9fnl;Host=localhost;Database=postgres;Persist Security Info=True
I guess that you're using devart's dotconnect for ado.net connectivity so you should import Devart.Data.PostgreSql and use PgSqlConnection instead of sqlconnection and pgsqlcommand instead of sqlcommand
As others have mentioned already, you need to use Npgsql. Also use imports to simplify your code. Example connection code:
import the assembly using Npgsql; then to get a connection and open it
using (var conn = new NpgsqlConnection(Properties.Settings.Default.postgresConnectionString))
{
// you other code here
}
This way your resources are managed automatically and you don't need to call the close method, also you need to change the type of command as #wingedpanther mentions. Reading a good tutorial or the docs mentioned will help a lot.
Also you need to fix your connection string as:
Server=localhost;User Id=postgres;Password=8loz9fnl;Database=postgres;Persist Security Info=True
And avoid putting your actual username and password.

About connecting sql server to c# (with ADO.NET)

I Have a problem in connecting my database to c# in connection string section
this is my code but when i run it , i get an error about this :
"Format of the initialization string does not conform to specification
starting at index 84"
My Code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection Cn = new SqlConnection(#" Server=TheAddress ; Database=MyDataBase.mdf ; integrated security='True' #");
Cn.Open();
SqlCommand Cm = new SqlCommand("", Cn);
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
I Cant Even Open My Connection (Error Happen in declaring SqlConnection)
I know its an Amature Question ... but its made me angry (i cant set it correctly)(with visual studio 2012 & sqlserver management studio 2012)
Looks like you have a "#" at the end you should remove from the connection string. You also might consider using the using statements when creating the SqlConnection and SqlCommand objects so they are properly disposed.
using (var Cn = new SqlConnection(#"Server=TheAddress;Database=MyDataBase.mdf;integrated security=True"))
{
Cn.Open();
using (var Cm = new SqlCommand("", Cn))
{
Cm.CommandText = "INSERT INTO Table1(ID_Food, Name_Food , TypeOfService_Food , Price_Food , Type_Food) VALUES (#ID_Food , #Name_Food , #TypeOfService_Food , #Price_Food , #Type_Food)";
Cm.Parameters.AddWithValue("#ID_Food", textBox1.Text);
Cm.Parameters.AddWithValue("#Name_Food", textBox2.Text);
Cm.Parameters.AddWithValue("#TypeOfService_Food", textBox3.Text);
Cm.Parameters.AddWithValue("#Price_Food", textBox4.Text);
Cm.Parameters.AddWithValue("#Type_Food", textBox5.Text);
Cm.ExecuteNonQuery();
Cn.Close();
}
}
you need to provide valid connection string .
Try This :
SqlConnection Cn = new SqlConnection(#"Data Source=TheAddress;Initial Catalog=MyDataBase.mdf;Integrated Security=True");
EDIT : from comments : as you are getting runtime excpetion please check wether you are able to communicate with the server or not.
Check this here

Categories

Resources