Stored Procedure in sql server 2005 - c#

I use the following function for insert the value in database through the stored procedure.but i have the exception in sqlConnection.Open();How to solve this?
try
{
string dbConnectionString = "something";
SqlConnection sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand("sp_Test", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id ", SqlDbType.Int).Value = TextBox1.Text;
command.Parameters.AddWithValue("#FullName", SqlDbType.VarChar).Value = TextBox2.Text;
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
}

Well, the error you are getting doesn't really have anything to do with stored procedures, but I can answer the question of "how to solve this?" in the context of the exception you are getting.
First, I hope you are not using "something" as the actual connection string to your sql server. You should be using a real connection string. Here are some various examples you can use to connect to SQLServer - http://www.connectionstrings.com/sql-server-2005
Using the first example from the above url
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
You'll want to change "myServerAddress" to the ip address or host name of the server. This could be "localhost" or it could be another computer you have on the network. Change "myDataBase" to the name of the database you created, and make sure the name matches exactly as the database might be configured with case sensitivity. And finally change "myUsername" and "myPassword" to the user and password of the account you use to access the server under Sql Server Management Studio.
Now, assuming you have actually done the above, here are some steps you can take to debug connection issues.
Ping the computer - from and command prompt type "ping servername" where servername is the name or ip address of the server that runs SQL Server. If you don't get a response from the server then you need to debug your local network.
If the server is running locally try using "." for the "myServerAddress" value. If it's sqlserver express edition, use the express format - ".\SQLExpress" or "myServerAddress\SQLExpress"
If SQL Server is running on another computer try each of the three links under the section "More Information" from this kb article - http://support.microsoft.com/kb/914277 That will ensure remote connections are supported.
But the real issue is that you cannot connect to the database. I recommend searching for solutions to that problem first. Or perhaps supply more information about your setup here on SO in a different question.
Hope that helps,
-Marcus

Related

How to connect remotely to MySQL server

What is the best way to connect remotely to MySQL server on domain ?
I want to make an desktop app or maybe it is easier to do it with asp.net ?
Use Mysql Workbench for desktop use to connect to Mysql Server.
For coding: Get Mysql client library for .net . It's called mysql connector. Add
using Mysql.Data; namespace
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html
Makes no difference what kind of application you are creating.
your code will look very similar like this one:
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=12345;database=test;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
1- I usually use HeidiSQL tool to connect to MYSQL server otherwise on localhost or remotely servers on CPanels.
most of CPanels allow to remote connection by adding % at access hosts field to enable me connect remotely anywhere.
from your cpanel go to the database tools then -> you will find link for Remote mysql -> then you can any IP address to make server allow to connect, if you want connect anywhere you put %.
Note: CPanels are little different each others.
2- if you want connect to mysql in your code, you make a normal connection after doing step 1.

Connect desktop c# application to online mySql databse

I have a windows form application in C# and sometimes I want to push some data table from this application to an online mySql server which is hosting all data for my website in PHP. To do that I've installed :
1- MySql for visual studio version 1.2.3
2- MySql Connector.Net 6.9
Also, I have enabled Remote MySql on the server so I can make the connection. I used the '%' wildcard for the meantime because my IP address is dynamic.
my basic c# connection code is as below :
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "Server=*******;Database=*******;Uid=******;Pwd=********;";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
MessageBox.Show("connected successfully..");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
Unfortunately, every time I run this code I am getting an error which says
"Unable to connect to any of the specified MySQL hosts".
I don't' know where the problem is. Is it something on the UNIX server which
blocks the connections or some other thing which I need to do. I am also new to the CPanel interface and how to deal with it.
I appreciate all the help provided.
Many Thanks.
http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
Did you see that? You can try it.
I know this is an old question but I had the same issue many years ago and the only way I could get it to work was to enable remote MySql on the server I was running. This basically means allowing remote connections to access the DB. This of course is very risky and poses a major security problem. You can limit connections from specific IPs, but in my opinion its best to have a local DB and then perhaps push updates to an online source somehow.

SQL Server Connection Timeout C#

First off I'd like to let everyone know I have searched my particular problem and can't seem to find what's causing my problem.
I have an SQL Server 2008 instance running on a network machine and a client I have written connecting to it.
To connect I have a small segment of code that establishes a connection to an sql server 2008 instance and returns a DataTable populated with the results of whatever query I run against the server, all pretty standard stuff really. Anyway the issue is, whenever I open my program and call this method, upon the first call to my method, regardless as to what I've set my Connection Timeout value as in the connection string, it takes about 15 seconds and then times out. Bizarrely though the second or third call I make to the method will work without a problem.
I have opened up the ports for SQL Server on the server machine as outlined in this article: How to Open firewall ports for SQL Server and verified that it is correctly configured. Can anyone see a particular problem in my code?
string _connectionString = "Server=" + #Properties.Settings.Default.sqlServer + "; Initial Catalog=" + #Properties.Settings.Default.sqlInitialCatalog +
";User Id=" + #Properties.Settings.Default.sqlUsername + ";Password=" + #Properties.Settings.Default.sqlPassword + "; Connection Timeout=1";
private DataTable ExecuteSqlStatement(string command)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (SqlDataAdapter adaptor = new SqlDataAdapter(command, conn))
{
DataTable table = new DataTable();
adaptor.Fill(table);
return table;
}
}
catch (SqlException e)
{
throw e;
}
}
}
The SqlException that is caught at my catch is : "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
This occurs at the conn.Open(); line in the code snippet I have included. If anyone has any ideas that'd be great!
Addendum If I ping the server it's <10ms response time. Additionally I'm getting the same behavior when using SQL Server Management studio (I've just tried this after writing this question as the thought just crossed my mind). I would presume that this has to be a network issue as opposed to a code issue as it also takes two attempts when using SQL Server Management studio. I realise I can implement an error check for connection failure and then re-attempt the connection (I should probably do this anyway) but this doesn't seem particularly 'clean' to me as it doesn't address the underlying problem. Does anyone here have any experience with this issue?
Edit
Although over a year later this question has been viewed over 4000 times, I've since discovered that although I /thought/ the firewall ports were opened, they actually weren't. I'd incorrectly assumed that you need to open the firewall in Windows to the port number that SQL Server uses, in my case I set it to allow connections on TCP port 1433, the firewall caused issues when attempting to establish an initial connection.
I discovered that the correct way to set it up was to set Windows Firewall to allow the SQL Server Instance executable through. To do this you need Add a Program in Windows Firewall, browse to the folder your sql instance resides in such as C:\Program Files (x86)\Microsoft SQL Server\MSSQL10_50.SQLINSTANCE\MSSQL\Binn and then add the sqlservr.exe file to the firewall rules.
You are setting the connection timeout value to 1 second. Drop it from connection string and try again.
Or the problem could be with the SQL select you are using. Could it be taking a long time. If so, the 2nd and 3rd calls would retrieve the cached values and thus run much quicker.

Error connecting to Amazon EC2 MySQL from C#

I have an AWS EC2 instance running. I've tried to make a connection to my MySQL like this in C#
MySqlConnection l_DBConn = new MySqlConnection();
l_DBConn.ConnectionString = "Server=my-ec2.compute-1.amazonaws.com;Port=3306;Database=mydatabase;uid=root;password=mypassword;port=3306;charset=utf8"
MySqlCommand command = l_DBConn.CreateCommand();
command.CommandText = "select * from users";
MySqlDataReader Reader = command.ExecuteReader();
The error received when I run the last line is "Connection must be valid and open.". I still can connect to my instance using Filezilla,Putty and MySQL WorkBench also(with SSH). And I'm using MySql.Data.MySqlClient in my code. Anyone has any idea about this? Is this because my instance does not allow remote access or a problem with my connection string?
Thank you in advance,
Wayne.
Edit: The problem is solved by adding l_DBConn.Open() and add my IP to the server using RANT ALL PRIVILEGES ON . TO root#'hostname' IDENTIFIED BY 'root-password'. Thanks!
Try calling l_DBConn.open() before executing the reader. The error implies that the connection is not open since you haven't explicitely opened it
Some ideas:
Make sure you can connect to your database locally first.
Is Sql Server setup to allow mixed authentication
Have you open port 3306 in the EC2 firewall and the windows firewall if you're running it.

What is the difference between Java and C# when it comes to connect to Sql Server Database?

I am writing an application requires to connect to sql server. I prefer to write the App in Java. but When I try to connect to the server I got the connection refused error. I am using JTDS JDBC driver. I think it is due to the port 1433 or 1434 are not open. The server is in my work place and I can not change the ports. But funny enough, I use c# writing the same thing, it connects successfully. is it because SqlConnection class in C# library works better with ms sql server? or am I doing something wrong here? FYI, the server we are using in work is MS SERVER 2003.
Sorry I did not provide any code earlier. One tricky part is that the server we have is called "SERVER" on the local network.
C#:
SqlConnection objConnection = new SqlConnection("Data Source= SERVER\\SQLEXPRESS;Initial Catalog=SSS;Persist Security Info=True;User ID=user;Password=pass");
SqlCommand objcommand = new SqlCommand();
string strSQL;
objcommand.Connection = objConnection;
strSQL = "select * from company where companyid = #companyID ";
try
{
objConnection.Open();
SqlDataReader Query = objcommand.ExecuteReader();
while (Query.Read())
{
MessageBox.Show(Convert.ToString(Query["clientRef"]));
}
objConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error Retreiving info: " + ex.ToString(), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
objConnection.Close();
}
As I am not really familiar with C#. I have got the code above from one of the colleges. and it returns the info correctly.
Java:
try{
Connection connection;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://network.local/SERVER\\SQLEXPRESS:1433/SSS","user","pass");
System.out.println("Connection succeed!");
}
catch (Exception e) {
e.printStackTrace();
}
The java code above got Network error IOException: Connection refused error.
FYI: I can ping server.network.local successfully. But when I telnet server.network.local 1433/1434, I got telnet: Unable to connect to remote host: Connection refused.
Check how your .NET app is connecting. It may be as simple as it using named pipes, which JTDS supports as well.
It might be that the defaults are different, are you setting the port when you initialise your driver
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
Something like this jdbc:jtds:sqlserver://nameofyourdatabaseserver.or.ipaddress:port/yourdatabasename
Try using the full dns name for your server or the IP address
At the following link you will find a useful tutorial which describes in detail how to connect to MS SQLServer database, both from Java and C#. It also describes how to query the database, pass and retrieve data and much more. Hope you find it useful: http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html

Categories