SQL Server within & using stored procedure - c#

Trying to create a asp.net c# form for learning purposes at home and i'm absolutely struggling to connect to my storedprocedure.
I'm definitely in the right database as when I start the database by cmdprompt and connect to it via datasource in visual design it connects and finds the stored procedure. So there must be something I am doing wrong? I've been searching Google for about 30-40 minutes now and everything I've tried hasn't resolved my issue. Any suggestions please?
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
public static int InsertEnquiry(string Name, string Subject, string Email, string Message, string Phone) {
//default ticketid of 0 which will be changed to -1 if an error or greater than 0 if successful
int TicketID = 0;
if (String.IsNullOrEmpty(Phone)) Phone = "0";
using (var conn = new SqlConnection(constring)) {
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "InsertEnquiry";
command.CommandType = CommandType.StoredProcedure;
//add the parameters to the sqlcommand
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#Subject", SqlDbType.NVarChar)).Value = Subject;
command.Parameters.Add(new SqlParameter("#Phone", SqlDbType.NVarChar)).Value = Phone;
command.Parameters.Add(new SqlParameter("#Email", SqlDbType.NVarChar)).Value = Email;
command.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar)).Value = Message;
// try run command and set TicketID to the row inserted into the table.
try {
conn.Open();
//run command
command.ExecuteNonQuery();
//return scope identity of row.
TicketID = (int)command.Parameters["#TicketID"].Value;
}
catch (Exception e) {
//show -1 to state there is an error
TicketID = -1;
}
}
return TicketID;
}
}

1st
I think you are connected to the wrong db, probably you are in master.
Run this piece of code and check the name of the database and see if it's the one that you want.
public static string checkDB()
{
string dbName = "";
using (var conn = new SqlConnection(constring))
{
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "select DB_NAME()";
command.CommandType = CommandType.Text;
// try run command and set TicketID to the row inserted into the table.
try
{
conn.Open();
//run command
SqlDataReader reader = command.ExecuteReader();
reader.Read();
dbName = reader[0].ToString();
}
catch (Exception e)
{
}
}
return dbName;
}
2nd
You are trying to get the value from the parameter #TicketID but you didn't specify this parameter as an output parameter.
command.Parameters.Add("#TicketID", SqlDbType.Int).Direction = ParameterDirection.Output;
EDIT1:
This is how do you put the db name in the connection string:
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;Initial Catalog=MY_DB_NAME";

Related

Stored procedure expects parameter but parameter is actually supplied?

I need to know why I am still getting this error
Stored procedure expects parameter which was not supplied
But I am actually sending this parameter.
The stored procedure in the database looks like this:
CREATE PROCEDURE SVC_BUSCA_MEDIO_LANDING
(#rut VARCHAR)
AS
BEGIN
SELECT utm_source
FROM landing_formulario
WHERE rut = #rut
END
And my .net code:
string result = string.Empty;
string connString = System.Configuration.ConfigurationManager.AppSettings["StPazWeb"].ToString();
string SVC_BUSCA_MEDIO_LANDING = "SVC_BUSCA_MEDIO_LANDING";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
try
{
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
command.CommandType = CommandType.StoredProcedure;
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
result = (string)reader["utm_source"];
}
}
catch (SqlException ex)
{
throw new Exception("Oops!." + ex.Message);
}
}
return result.ToString();
Any idea what can be happening?
For some reason you create the command twice, with the second instantiation replacing the first, however on the second one you don't set the command type, and as a result your parameter is being ignored.
Try:
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = SVC_BUSCA_MEDIO_LANDING;
command.Parameters.AddWithValue("#rut", rut);
You're using:
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
but you're reseting the command at:
command = new SqlCommand(command.CommandText, connection);
Try instead:
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SVC_BUSCA_MEDIO_LANDING";
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);

Sending Declared Strings as query to write in SQL Server Using .NET

This is the demo code to a project I can't really get to send the "hisname" and "hisage" declared variables as a query. I actually need to send a query for each time the user enters the name and age those names and age must be sent as a query to the database.
static void Main()
{
string hisname;
int hisage;
Console.WriteLine("Hello! Have you met a new friend?");
string ans = Console.ReadLine();
Console.ReadLine();
if (ans == "y")
{
Console.WriteLine("Amazing! Whats his Name?");
hisname = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("Whats his age?");
hisage = Convert.ToInt16(Console.ReadLine());
Console.ReadLine();
Console.WriteLine("Do you want me to store it?");
Console.ReadLine();
string ans2 = Console.ReadLine();
if (ans2 == "y")
{
string SQLConnectionString = "Server=tcp:MYSERVER.database.windows.net,1433;Database=friendsadded;User ID=MYID;Password=MYPASS;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
// Create a SqlConnection from the provided connection string.
using (SqlConnection connection = new SqlConnection(SQLConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = #"INSERT INTO [myfriends] ([Friend], [Age]) VALUES ( N'hisname', 'hisage')";
// command.CommandText = #"SELECT TOP 10 UID, FRIEND, AGE FROM dbo.myfriends";
connection.Open();
}
}
}
}
}
}
Here the friendsadded is the database and myfriends is the table under it. I want it to add the names and age of the new entries to the database.
Here is an example of using parameters for this instead of passing through user entered data which is vulnerable to sql injection.
using (SqlConnection connection = new SqlConnection(SQLConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = #"INSERT INTO [myfriends] ([Friend], [Age]) VALUES ( #hisname, #hisage)";
command.Parameters.Add("#hisname", SqlDbType.VarChar, 10).Value = hisname;
command.Parameters.Add("#hisage", SqlDbType.Int).Value = hisage;
connection.Open();
command.ExecuteNonQuery();
}

sql server retrieve and update (windows phone 7)

I have a retrieve code of:
[WebMethod]
public List<Hawker> retrievehawker()
{
List<Hawker> retrievehawker = new List<Hawker>();
string qry = #"select hawkername, address, postal, xcoord, ycoord, popularity from uploadphoto";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
SqlDataReader mySqlDataReader = cmd.ExecuteReader();
while (mySqlDataReader.Read())
{
Hawker retrieveHawker = new Hawker();
retrieveHawker.hawkername = Convert.ToString(mySqlDataReader["hawkername"]);
retrieveHawker.address = Convert.ToString(mySqlDataReader["address"]);
retrieveHawker.postal = Convert.ToString(mySqlDataReader["postal"]);
retrieveHawker.xcoord = Convert.ToDouble(mySqlDataReader["xcoord"]);
retrieveHawker.ycoord = Convert.ToDouble(mySqlDataReader["ycoord"]);
retrieveHawker.popularity = Convert.ToDouble(mySqlDataReader["popularity"]);
retrievehawker.Add(retrieveHawker);
}
mySqlDataReader.Close();
conn.Close();
return retrievehawker;
}
and a setpopularity of :
[WebMethod]
public int SetPopularity()
{
string qry = #"update uploadphoto set popularity=popularity+1";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = qry;
conn.Open();
int status = cmd.ExecuteNonQuery();
conn.Close();
return status;
}
How can I combine them together so that based on a selection of a place in the windows phone 7, of a button click, then it will trigger the setpopularity. Right now the code for set popularity is adding the whole column of +1 to popularity. Help please.
You need to pass to your SetPopularity method the primary key (or another unique value) of your photo table.
In that way you could change your sql command to update only the record required
[WebMethod]
public int SetPopularity(string hawkername)
{
string qry = #"update uploadphoto set popularity=popularity+1
WHERE hawkername=#hawk";
using(SqlConnection conn = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand(qry, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#hawk", hawkername);
int status = cmd.ExecuteNonQuery();
return status;
}
}
The string passed to the method is your primary key (or an unique value better if indexed) and could be used in the WHERE clause.
Notice also the using statement around the disposable objects and the parameterized query approach to avoid Sql Injections and parsing problems.

Error running SQL query on C# - OleDbException was unhandled, characters found after end of SQL statement

Whenever I run the below event on C# I get the following error message - OleDbException was unhandled, characters found after end of SQL statement at the int affectedRows = (int)command.ExecuteNonQuery(); line. Any idea how I can fix it?
private void save_btn_Click(object sender, EventArgs e)
{
if (pgpText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: PGP");
}
else if (teamText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: Team");
}
else
{
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET PGP=pgp,Team=team WHERE pgp=pgp; SELECT ##ROWCOUNT;";
conn.Open();
int affectedRows = (int)command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (PGP,Team) VALUES (pgp,team)";
command.ExecuteNonQuery();
}
}
}
}
I suspect you were actually trying to use parameters - note that your pgp and team variables in C# aren't being used at all in your code. I suspect you want something like:
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET Team=? WHERE PGP=?";
command.Parameters.Add("team", OleDbType.VarChar).Value = team;
command.Parameters.Add("pgp", OleDbType.VarChar).Value = pgp;
conn.Open();
int affectedRows = (int) command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (Team, PGP) VALUES (?, ?)";
// Parameters as before
command.ExecuteNonQuery();
}
}
Note that I've removed the "SELECT ##ROWCOUNT" part from your update - that's not needed as ExecuteNonQuery returns the number of rows affected anyway.
A couple of other notes:
For most database providers, you'd use named parameters instead of positional ones, e.g. VALUES (#pgp, #team) and then use the parameter names... but the OLE DB provider in .NET doesn't support these.
Do not use string concatenation for SQL as another answer (possibly deleted by the time you read this) has suggested - that paves the way for SQL Injection attacks and conversion issues. (And it's messy.)

Connect to SQLite using C#

I got the following error:
Input string was not in a correct format
Can anyone help to me? Here is my input parameters and method:
public void insertSQL(Dictionary<string,object> objects, string dbConnectionString)
{
openConnection(dbConnectionString);
SQLiteCommand command = new SQLiteCommand(sqliteCon);
command.CommandText = "INSERT INTO AppUser VALUES(#name, #surname)", objects, "Data Source=sample.s3db"
command.CommandType = CommandType.Text;
foreach (var param in objects)
{
command.Parameters.Add(new SQLiteParameter(param.Key,SqlDbType.NVarChar){ Value = (String)param.Value} );
Console.WriteLine(command.Parameters.Count);
}
command.ExecuteNonQuery();
closeConnection();
}
You must tell for which columns you are presenting values (other will get their default values)
Something like :
INSERT INTO AppUser (name,surname) VALUES(#name, #surname) ...
Parameters' name in query should be equal to parameters you assign values to:
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "...";
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = name;
command.Parameters.Add("#surname", SqlDbType.NVarChar).Value = value;
connection.Open();
command.ExecuteNonQuery();
}

Categories