what is wrong in my code to call a stored procedure - c#

I Have created a Stored procedure dbo.test as follows
use sample
go
create procedure dbo.test as
DECLARE #command as varchar(1000), #i int
SET #i = 0
WHILE #i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),#i)
SET #i = #i + 1
END
Now i am created a c# console application to call the stored procedure as follows
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
try
{
conn = new SqlConnection("Server=(TEST\\SQL2K5EXPRESS);DataBase=sample,IntegratedSecurity=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("sample.dbo.test", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
rdr[0], rdr[1]));
}
}
catch(Exception ex)
{
Console.writeLine(ex.message);
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Program p= new Program();
p.RunStoredProc();
Console.Read();
}
}
}
O/P:
Hello World
//Could not find stored procedure 'test'.
A network-related or instance-specific error occurred while establishing a conne
ction to SQL Server. The server was not found or was not accessible. Verify that
the instance name is correct and that SQL Server is configured to allow remote
connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Serve
r/Instance Specified)
But when i try to run the program it was closing so i debugged the program then at exactly at executeReader() method it was showed that can not find the stored procedure "dbo.test"
and when i give the "EXEC dbo.test" at SSMS it display the result as i expected.
waht is wronng with this any Help greatly Appreciated.

Why are you looking in the master database?
Also, your code needed some cleanup:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
Console.WriteLine("\nTop 10 Most Expensive Products:\n");
using (SqlConnection conn =
new SqlConnection(
"Server=(local);DataBase=master;IntegratedSecurity=SSPI"))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("dbo.test", conn) {
CommandType = CommandType.StoredProcedure})
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
rdr[0], rdr[1]));
}
}
}
}
}
}
}

I would suggest it is related to teh permissions granted to the stored procedure.
Check out "GRANT EXECUTE <storedProc> TO <User>" you could also check the permissions in SSMS by right clicking on the stored proc.
I understand this is a test stored proc but it is not optimal to create stored procedures in the master database.
All the best :)

Just change your connection string:
conn = new SqlConnection("Server=(local);DataBase=master;IntegratedSecurity=SSPI");
You're hitting the master database. You want to hit whatever your database is called.
Alternatively, call the stored proc as dbname.dbo.test.

First of all - there's typo in your connection string - you need to use all semicolons - not semicolon once and commas the other time. Between DAtaBase= and IntegratedSEcurity, you have a comma - plus, it has to be "Integrated Security" (with a space!). Check out www.connectionstrings.com for the details on how to properly create a connection string.
Your original connection string in your post:
conn = new SqlConnection(
"Server=(TEST\\SQL2K5EXPRESS);DataBase=sample,IntegratedSecurity=SSPI");
should really be:
conn = new SqlConnection(
"Server=(TEST\\SQL2K5EXPRESS);DataBase=sample;Integrated Security=SSPI");
Once that would work, I think the main problem is that you're trying to pass in a SQL statement in the parameter #command to the stored procedure, which you execute inside the stored procedure (not in your current post, but in others you've posted), and you want to read out the rows returned by that statement.
But you have no way of being sure (short of parsing the SQL statement you're passing in) whether or not that SQL statement will actually indeed return values or whether it's a DDL statement like INSERT, CREATE TABLE or something.
So you have ADO.NET, calling a stored proc, which dynamically executes an arbitrary SQL statement, and you still want to be able to retrieve those results....
In my opinion, you need to rearchitect your approach - this will never work reliably - find another way to do what you're trying to do - there must be a way to do this with less dynamic execution of SQL inside a stored proc and stuff........ there's gotta be an easier way!
Marc

Have you tried just using "test" instead of "dbo.test"?

Your stored procedure doesn't return any results. Change your PRINT into SELECT.
You may be getting the error because ADO.NET doesn't know how to react to the status messages the print statement causes.

The SQL error you see is connecting to the server. It doesn't even get that far, so it isn't related to permissions at all. As far as your client goes, you'd get the same error if you connected to "Server=GroverCleveland\Instance1" (assuming it doesn't exist on your network).
I think that the problem is that you are wrapping the server name in parens, if you can connect to it fine using other SQL clients on the same client box. Try the following:
conn = new SqlConnection("Server=TEST\\SQL2K5EXPRESS;DataBase=sample;IntegratedSecurity=SSPI");
Marc is right about the semicolon, btw. Check out connectionstrings.com for details on that...

Related

Executing Stored Procedure using C#

I have a procedure named as Get_Added_Request_ID and using this procedure I need to get returned the Request_ID value (VARCHAR2). I have referrd plenty of docs released by Oracle and Microsoft but still I could not find a good solution may be because I am a new learner for Oracle and ASp.NET. Please someone help me in this issue. Thanks in advance
-- Parameter Type Mode Default?
-- ATTR_ VARCHAR2 IN
-- REQUEST_ID VARCHAR2 OUT
Please view this link for the documentation on how to connect to oracle by using oracle data provider
You should use oracle data provider from this link for connecting oracle.
the example code for your scenario will be
Using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;
namespace CallingOracleStoredProc
{
class Program
{
static void Main(string[] args)
{
using (OracleConnection objConn = new OracleConnection("Data Source=*your datasource*; User ID=*Your UserID*; Password=*Your Password*"))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "Get_Added_Request_ID";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("ATTR_", OracleType.NVarChar).Value = "test";
objCmd.Parameters.Add("REQUEST_ID", OracleType.NVarChar).Direction = ParameterDirection.Output;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
System.Console.WriteLine("The Request ID is {0}", objCmd.Parameters["REQUEST_ID"].Value);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: {0}",ex.ToString());
}
objConn.Close();
}
}
}
}
use execute scalar which return 1 row - 1 column value & store it in appropriate variable
For e.g :- SqlHelper.ExecuteScalar(_connectionString, CommandType.StoredProcedure, "Get_Added_Request_ID", null);
note :- ExecuteScalar is came from nuget Microsoft.Application Block

Execute any Raw SQL Query

IS it possible to execute a raw SQL command of any type (SELECT, UPDATE, DELETE....) in C#. I am looking to add a feature similar to the SQL Server Management Studio query window where I can just type in any SQL command and it executes it. In my case I am not worried about sql injection, I know this risk with this feature. All the connection parameters are passed to me (I have a valid connection string), but I know nothing about the database itself. The SQL command is also syntactically correct before I get the command. I cannot seem to find a solution that will work in all cases, probably just overlooking the obvious solution.
Here is an ADO example for you
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"UPDATE [dbo].[USR_Users] SET [Active] = 1 WHERE Id = 1";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
You can simply use ADO .NET and show the results of the query if it executed successfully or not, just put the following code in the event handler when you want to execute your query:
using (SqlConnection conn = ConnectionClass.GetInstance().Connection())
using (SqlCommand cmd = new SqlCommand(TextBoxQuery.Text, conn))
{
conn.Open();
TextBoxNoOfRowEffected.Text = cmd.ExecuteNonQuery().ToString();
}
SqlCommand.ExecuteNonQuery() Documentation

MySQL insert command using prepared statement and placeholders is not working

I built a MySql database and a C# Windows GUI form to with textbox fields and a timedate picker to populate a table named 'job' in my database.
I have read a few posts on this site about the importance of using prepared statements to prevent sql injection attacks and I tried to use this security feature in my code.
However it is not working. I am a web designer but very new to programming. I tried different code variations at the insert command still won't work. The samples I have found on this form involve using prepared statements with PHP, which is not what I am using.
I get the following error message: You have an error in your SQL syntax; check the manual or your MySQL server version for the right syntax to use near 'jobTitle, this.dateTimePickerJobLastUpdated')' at line 1
Does anyone know what I am doing wrong and how I can fix this?
This is the MySQL statement for the table.
CREATE TABLE job (
job_code VARCHAR(6) NOT NULL DEFAULT '',
job_title VARCHAR(30) NOT NULL DEFAULT '',
job_last_update DATE NOT NULL,
PRIMARY KEY (job_code)
)ENGINE=InnoDB CHARSET=utf8;
And this is my C# for the event handler that will save the data entry from the windows form to the database.
private void btnSaveJobsTable_Click(object sender, EventArgs e)
{
String myConnection = #"server=localhost; database=beautyshopdb; username=$$$$; password=$$$$$$";
MySqlConnection Connect = null;
try
{
Connect = new MySqlConnection(myConnection);
Connect.Open(); //open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholder is #name.
//Using prepared statements is faster and secure.
String insertQuery = "INSERT INTO beautyshopdb(job) VALUES(#jobCode, #)jobTitle, #lastUpdated)";
MySqlCommand cmdInsertJobsToDataBase = new MySqlCommand(insertQuery, Connect);
cmdInsertJobsToDataBase.Prepare();
//we will bound a value to the placeholder
cmdInsertJobsToDataBase.Parameters.AddWithValue("#jobCode", "this.txtEnterJobCode.Text");
cmdInsertJobsToDataBase.Parameters.AddWithValue("#jobTitle", "this.txtEnterJobTitle.Text");
cmdInsertJobsToDataBase.Parameters.AddWithValue("#lastUpdated", "this.dateTimePickerJobLastUpdated");
cmdInsertJobsToDataBase.ExecuteNonQuery(); //execute the mysql command
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (Connect != null)
{
Connect.Close(); //close the connection
}
}
}
Thank you!
I'm not a C# developer, but this doesn't look right, I think you have an extra parenthesis before jobTitle:
String insertQuery = "INSERT INTO beautyshopdb(job) VALUES(#jobCode, #)jobTitle, #lastUpdated)";
Also you seem to be putting variable references inside quotes as if they are string constants. I would expect these to require no quotes.
cmdInsertJobsToDataBase.Parameters.AddWithValue("#jobCode", "this.txtEnterJobCode.Text");
Should be:
cmdInsertJobsToDataBase.Parameters.AddWithValue("#jobCode", this.txtEnterJobCode.Text);

.NET and sql server database link

I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.

Where have I gone wrong with this c# simple sql insert

Final Note: After adding the executeNonQuery AND after I changed the connection string from Filename=|DataDirectory|\testconn.mdf to Filename=c:\Documents........\testconn.mdf. My data began to insert into my table. Thanks all for the help.
While working with this sql insert I find that the code runs without any exceptions but after going to database explorer and looking at the show table data, the data was not inserted. Originally I wasn’t using the transaction code but read on this site this may be the problem it also runs without an exception but still does not actually insert into the table. While stepping through I can see where the status changes from open to close following the conn.Open() and connClose() statements. In addition for best practice is there a cleaner/better way to write my SqlConnection string as well as my SqlCommand strings? Thank you My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Transactions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
CommittableTransaction MASTER_TRANSACTION = new CommittableTransaction();
// 1. Instantiate the connection
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\testconn.mdf;Integrated Security=True;User Instance=True");
try
{
// 2. Open the connection
conn.Open();
conn.EnlistTransaction(MASTER_TRANSACTION);
// 3. Pass the connection to a command object
SqlCommand cmd = new SqlCommand("INSERT INTO Client_Master(Client_ID, Client_First, Client_Last) VALUES('2', 'Joe', 'Shmoe')", conn);
MASTER_TRANSACTION.Commit();
}
finally
{
conn.Close();
}
}
}
}
try calling
cmd.ExecuteNonQuery();
before MASTER_TRANSACTION.Commit();
I think you need to call an execute method on the the command object.
you need to execute the command via cmd.ExecuteNonQuery() as well.
Try cmd.ExecuteNonQuery() to execute the SQL command
MSDN Link
Yes, execute the cmd and then right before the line with "finally" add:
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
and it will show other exceptions if any.
And you don't really need the overhead of a transaction for a single insert.... and if you did you should have a rollback in the Exception block.
You have to execute your command. i.e.
// 3. Pass the connection to a command object
SqlCommand cmd = new SqlCommand("INSERT INTO Client_Master(Client_ID, Client_First, Client_Last) VALUES('2', 'Joe', 'Shmoe')", conn);
cmd.ExecuteNonQuery();
MASTER_TRANSACTION.Commit();
Check here for more info.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
You need to execute the SQL command. Try
cmd.ExecuteNonQuery()
You're creating the command but not doing anything with it. You're missing a:
cmd.ExecuteNonQuery();
Also, you should think of encapsulating the connection with a using statement, as it disposes it automatically, like:
using(SqlConnection conn = new SqlConnection(connectionString))
{
}
Try adding a "catch" block to the "try" and "finally" so you can see if there is an error occurring.
Currently, you are missing the actually execution of the statement. Add the following to fix that:
cmd.ExecuteNonQuery();
In addition, why are you using a Transaction? Transactions are useful when executing multiple statements to ensure an "all or none" execution. You are just inserting one row.
your cmd is:
INSERT INTO Client_Master(Client_ID, Client_First, Client_Last)
VALUES('2', 'Joe', 'Shmoe').
and i think that problem is here. with Client_ID column. You have set this column as primary key. but you are going to insert '2' in every time. for this reason it gives you
System.Data.SqlClient.SqlException was caught Message=Violation of PRIMARY KEY
constraint 'PK_Client_Master'. Cannot insert duplicate key in object dbo.Client_Master.
you can make Client_ID column as autoincrement

Categories

Resources