How to Use Parameters "@" in an SQL Command in Vb

How to use parameters @ in an SQL command in VB

You are on the right path to avoiding Bobby Tables, but your understanding of @ parameters is incomplete.

Named parameters behave like variables in a programming language: first, you use them in your SQL command, and then you supply their value in your VB.NET or C# program, like this:

MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = @TicBoxText WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("@TicBoxText", TicBoxText.Text)

Note how the text of your command became self-contained: it no longer depends on the value of the text from the text box, so the users cannot break your SQL by inserting their own command. @TicBoxText became a name of the variable that stands for the value in the text of the command; the call to AddWithValue supplies the value. After that, your ExecuteReader is ready to go.

Vb 2015 query with parameters not working

In your original query, when testing against idcliente, you treat strName as a number (no quotes round it), but for all the other fields you treat it like a string. So you're implying it could potentially contain a number or a string. This is problematic, if you type a number, and the parameterised version of the query now treats it like a string in all cases, then it won't match the numeric value of idcliente in the DB and therefore you may get no results.

To clarify: if your input is a number, but your query thinks it's a string (because of the data type in the param), it will not match against any numeric field in the database. 12345 != "12345".

You need to define separate parameters for these scenarios. You can pass the same value into them, but in one case set the parameter's datatype to varchar and in the other case to int (you might need to check if the value can be parsed as a number before you do this, otherwise it will likely crash. In that case just set it null or 0 or something that won't make an accidental match).

How to pass a parameter from vb.net

//These are the date variables.. if u need them seperately

Dim TodayDt As DateTime = DateTime.Today
Dim Tomorrow As DateTime = DateTime.Today.AddDays(1)
Dim TodayEnd as DateTime
TodayEnd = Tomorrow.AddSeconds(-1)

//This is the SQL Command that executes in SQL Server

  SELECT
SUM(QTY) AS Discounts
FROM
dbo.fFinancialDataFull('Date Range Report', startdate , enddate, '1', '1', 'ALL', 'ALL', 'ALL', 'ALL', '1', '1', '1', '1', '1') AS fFinancialDataFull_1
WHERE ReportCategoryID = 62
AND startdate = TodayDt
AND enddate = TodayEnd AS unlimitedtbl

//This is the function u need to write to make the same SQL run on VB

Public Function GetValueByDates() As String
Dim TodayDt As DateTime = DateTime.Today
Dim Tomorrow As DateTime = DateTime.Today.AddDays(1)
Dim TodayEnd as DateTime
TodayEnd = Tomorrow.AddSeconds(-1)
Dim ReportCategoryID = 62

Dim sql As String = " SELECT
SUM(QTY) AS Discounts
FROM
dbo.fFinancialDataFull('Date Range Report', startdate , enddate, '1', '1', 'ALL', 'ALL', 'ALL', 'ALL', '1', '1', '1', '1', '1') AS fFinancialDataFull_1
WHERE ReportCategoryID = @ReportCategoryID
AND startdate = @TodayDt
AND enddate = @TodayEnd AS unlimitedtbl"

Using cn As New SqlConnection("Your connection string here"), _
cmd As New SqlCommand(sql, cn)

cmd.Parameters.Add("@TodayDt", SqlDbTypes.DateTime).Value = TodayDt
cmd.Parameters.Add("@TodayEnd", SqlDbTypes.DateTime).Value = TodayEnd
cmd.Parameters.Add("@ReportCategoryID", SqlDbTypes.int).Value = ReportCategoryID
Return cmd.ExecuteScalar().ToString()
End Using
End Function

vb.net execute sql command with variables

The string values you're concatenating aren't surrounded by quotes, so the database identifies them as column names - and then fails since there are no such columns. Moreover, this leaves your program vulnerable to SQL Injection attacks.

A better approach would be to use bind variables:

cmd.CommandText = "insert into utilisateur (login, password, type) value (@P1, @P2, @P3)"
cmd.Parameters.AddWithValue("@P1", TextBox3.Text)
cmd.Parameters.AddWithValue("@P2", TextBox4.Text)
cmd.Parameters.AddWithValue("@P3", ListBox1.SelectedItem())
cmd.ExecuteNonQuery()

Calling SQL Server stored procedure from VB.NET application. Output parameter is coming back blank

You missed '@' in the parameter name in the SP. It should be

select @numberPotentialMatches = count(*) ...

What you did was selecting count(*) and setting numberPotentialMatches as column alias.

Also, don't access the SqlCmd after it's disposed.

SQL parameters asp.net(vb.net)

If your username field is an unique index (meaning that you don't have two username with the same value) then your query could be rewritten without using a SqlDataReader

Dim sq As String = "SELECT username FROM standing WHERE username = @user"
Using con SqlConnection(Sql.ConnectionString)
Using cmd As New SqlCommand(sq, con)
cmd.Parameters.Add("@user", SqlDbType.VarChar)
cmd.Parameters("@user").Value = "contesttest"
con.Open()
Dim username = cmd.ExecuteScalar
If userName IsNot Nothing Then
'Something..
Else
'Something else..
End If
End Using
End Using

ExecuteScalar return the first column of the first row retrieved by your command. In the case you column is a unique index/primary key then you have just one row and you return just the username. So if there is something returned then you have found your user

Pass Array Parameter in SqlCommand

You will need to add the values in the array one at a time.

var parameters = new string[items.Length];
var cmd = new SqlCommand();
for (int i = 0; i < items.Length; i++)
{
parameters[i] = string.Format("@Age{0}", i);
cmd.Parameters.AddWithValue(parameters[i], items[i]);
}

cmd.CommandText = string.Format("SELECT * from TableA WHERE Age IN ({0})", string.Join(", ", parameters));
cmd.Connection = new SqlConnection(connStr);

UPDATE: Here is an extended and reusable solution that uses Adam's answer along with his suggested edit. I improved it a bit and made it an extension method to make it even easier to call.

public static class SqlCommandExt
{

///
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
///

/// The SqlCommand object to add parameters to.
/// What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.
/// The array of strings that need to be added as parameters.
/// One of the System.Data.SqlDbType values. If null, determines type based on T.
/// The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.
public static SqlParameter[] AddArrayParameters(this SqlCommand cmd, string paramNameRoot, IEnumerable values, SqlDbType? dbType = null, int? size = null)
{
/* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually.
* Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
* IN statement in the CommandText.
*/
var parameters = new List();
var parameterNames = new List();
var paramNbr = 1;
foreach (var value in values)
{
var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
parameterNames.Add(paramName);
SqlParameter p = new SqlParameter(paramName, value);
if (dbType.HasValue)
p.SqlDbType = dbType.Value;
if (size.HasValue)
p.Size = size.Value;
cmd.Parameters.Add(p);
parameters.Add(p);
}

cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(",", parameterNames));

return parameters.ToArray();
}

}

It is called like this...

var cmd = new SqlCommand("SELECT * FROM TableA WHERE Age IN ({Age})");
cmd.AddArrayParameters("Age", new int[] { 1, 2, 3 });

Notice the "{Age}" in the sql statement is the same as the parameter name we are sending to AddArrayParameters. AddArrayParameters will replace the value with the correct parameters.

How do you pass an output parameter from vb.net to a mysql stored procedure?

Please try this

Create Stored Procedure in MySQl like

DELIMITER $$
DROP PROCEDURE IF EXISTS `tempdb`.`GetCity` $$
CREATE PROCEDURE `tempdb`.`GetCity`
(IN cid INT,
OUT cname VarChar(50)
)

BEGIN

SET cname = (SELECT CityName FROM `City` WHERE CID = cid);

END $$

DELIMITER ;

And Your vb.net code like

Dim conn As  New MySqlConnection()
conn.ConnectionString = "server=localhost;user=root;database=tempdb;port=3306;password=******;"
Dim cmd As New MySqlCommand()

conn.Open()
cmd.Connection = conn
cmd.CommandText = "GetCity"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@cid", "1")
cmd.Parameters("@cid").Direction = ParameterDirection.Input

cmd.Parameters.AddWithValue("@cname", MySqlDbType.String)
cmd.Parameters("@cname").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()

Console.WriteLine("City Name: " & cmd.Parameters("@cname").Value) //Access Your Output Value

Let me know if you have any problem...

Thanks



Related Topics



Leave a reply



Submit