Informix database via odbc connection - Issue with insert stored procedure - c#

This stored proc. - SP_insertinfo inserts an entry into a table.
I am connecting via an ODBC DSN to an informix database.
This is my code, this one doesn't throw me an error or doesn't insert a record.
I am connected via sequeLink 3.10 32-bit driver, my application runs on 64-bit OS.
Trying to identify why the data is not getting inserted(when i put a breakpoint, get the parameterized statement into the actual DB, there it inserts for the same data, however it fails when run from the application code).
int rowsInserted = command.ExecuteNonQuery(); //This line is always
returning -1 and data doesn't get inserted.
Any thoughts/idea will be very much helpful?
private void InsertInfo()
{
try
{
using(var connection = new OdbcConnection("dsn=mydsn;UID=myusername;PWD=****;"))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.Connection = connection;
command.CommandText = "execute procedure SP_insertinfo(?,?)";
command.Parameters.Clear();
//Insert parameter values
var paramId = new OdbcParameter("ID", OdbcType.Int) { Value = Convert.ToInt32(txtID.Text.Trim()) };
command.Parameters.Add(paramId);
var paramCountry = new OdbcParameter("Country", OdbcType.VarChar, 25) { Value = txtCountry.Text.Trim() };
command.Parameters.Add(paramCountry);
connection.Open();
int rowsInserted = command.ExecuteNonQuery(); //This line is always returning -1 and data doesn't get inserted.
if (rowsInserted > 0)
{
MessageBox.Show("Insert data saved.");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString()) ;
}
}

At first try to execute your procedure as simple statement, not as prepared statement. This will look like:
command.CommandText = "execute procedure SP_insertinfo(1, 'Poland')";
connection.Open();
int rowsInserted = command.ExecuteNonQuery();
This way you will see if it is problem with prepared statement.
Try to execute execute procedure SP_insertinfo(1, 'Poland') via dbaccess (Informix tool). This way you will see if it is ODBC issue.
If it do not work with dbaccess then you will have to debug SP_insertinfo. If it work, then problem is with ODBC. Then I suggest enabling ODBC trace in ODBC Manager and analyzing log it will produce.

After a long research, i found out that, in order for ODBC dsn to work correctly with sequeLink, the drivers should match the version of operating system, i am using windows 7.0 64-bit, my dsn was 32-bit , i used a 64-bit dsn in order to work with 64-bit OS.

Related

Using MySQL stored procedure in Asp.Net C#

I can not find what is the error in this code. According to me it's good and hope to execute properly but I am getting an error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.7.11]
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ViewBatchByID' at line 1
My code Is
string Message = null;
OdbcCommand Cmd = new OdbcCommand();
Cmd.Connection = Connection.con;
Cmd.CommandText = "ViewBatchByID";
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#p0", 1);
try
{
Cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Message = ex.Message.ToString();
}
HERE ViewBatchByID is my stored procedure and it's working fine from server.
Check the connection settings for the server. Is the Database set?
Driver={SQL Server};Server=(local);Trusted_Connection=Yes;Database=AdventureWorks;

Run TSQLScripts via the Web Page in c# ASP.Net

I am trying to build the Web Page which can be used to run the TSQL scripts online.
My DB has so many databases and I am using the System Administrator account to execute these scripts.
After building the web page,
I can run the simple CRUD statements successfully in all databases
I can run the DML statements only for the default connected database, which is MyDB1.
Whenever, I create the new Object, it sits in the MyDB1. But I want to run / create objects in another DB.
I tried to run the following command, which is very simple and it works perfectly in SSMS.
USE MyDB2
GO
CREATE PROCEDURE [dbo].MyProc
AS
BEGIN
INSERT INTO
dbo.Table1
(
FieldA
, FieldB
, FieldC
)
VALUES
(
'AAA'
, 'BBB'
, 'CCC'
)
END
But I am getting the error message:
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
My c# code to execute the posted script is here:
DataTable dt = new DataTable();
try
{
using (SqlConnection cn = new SqlConnection("MyConnString"))
{
cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn);
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (dr.HasRows)
{
dt.Load(dr);
}
dr.Close();
}
cn.Close();
}
}
catch (Exception ex)
{
//Log Error
}
If I removed, USE statement, it was ok, but it created the object in the default DB which is MyDB1. How I can tweak my code to run it in MyDB2?
USE is an SSMS command, not a SQL statement.
Change your connect string to specify the appropriate database.

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);

How to execute a update statement using Oracle ODP.Net in C#

I am using Oracle.DataAccess.Client to work with Oracle database in my ASP.Net application. There is no help documentation in MSDN for ODP.Net and Oracle's documentation is really really bad. I am not able find the answer to this simple question.
Is it not possible to execute a simple update statement without having to build a dataset object and updating the dataset?
How to execute an update statement using Oracle ODP.Net in C#?
I will need to check the exact syntax, but here is some quick code off the top of my head
using (OracleConnection con = new OracleConnection(...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update table set col1 = :param1, col2 = :param2 where key = :keyValue";
cmd.Parameters.AddWithValue("param1", 1);
cmd.Parameters.AddWithValue("param2", "Text data");
cmd.Parameters.AddWithValue("keyValue", "1");
cmd.ExecuteNonQuery();
}
The above creates a command object sets the command up to execute an SQL Update statement, in this example I show one way to setup a parameterized query, you should always go with a parameterized query. Once the command is setup you just call ExecuteNonQuery to actually execute the command.
So after a bit of sleuthing and working this one out for a while, I found that the method I used to add a new parameter to the connection command is as follows. I did not find the method as was stated in the previous post. Mind you I am using a query object that I am passing the values around with.
public Boolean InsertMethod(Query _query)
{
var success = false;
var queryString = string.Format(#"INSERT INTO TABLE(ID, OWNER, TEXT) VALUES (TABLE_SEQ.NEXTVAL,:OWNER, :TEXT)");
try
{
using (OracleConnection con = new OracleConnection(ConString))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = queryString;
cmd.Parameters.Add("OWNER", _query.Owner);
cmd.Parameters.Add("TEXT", _query.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated > 0) success = true;
}
return success;
}
catch (Exception ex)
{
log.Error(ex);
throw;
}
}
Further to #Chris's answer, here is the documentation page of OracleParameter class which has sample code on using OracleCommand to execute Updates.
EDIT: Here is the entry point for ODP.net documentation.

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