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

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

Related

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

removing form from c# code?

I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.

Why won't C# show the table

I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow this C# ADO.NET tutorial (currently on step 2), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in WebApplication1's Default.aspx page.
For a while, I thought it was my connection string, conn, and I wasn't naming the "Data Source" attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is AZUES-221\JDOESQLSERVER
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
Thanks in advance
As your example seems to be a WebProject try to put your code within Page_Load eventHandler. Afterwards you should try to print your data to the Debug window or to a control within your webPage.
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
You may it find very useful to have a look at databound controls or just use another type of project (eg winForm, console, ...)
Create a Console application instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.
Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
SqlConnection conn = new SqlConnection(#"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
Source: Connection Strings Reference
why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]);

Where/how do I write T-SQL in my C# code and get the result (Visual Studio 2008)

I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
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 Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement

what is wrong in my code to call a stored procedure

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...

Categories

Resources