SqlCommand (CommandType Text) retrieve param collection - ado.net

Is there a way to get the parameter collection from SqlCommand when CommandType = Text?
For instance:
string MyDinamicSql = #"SELECT * FROM USERS where USERName = #Param1 and USERLogin=#Param2";
SqlCommand comand = connection.CreateCommand();
comand.CommandText = MyDinamicSql;
comand.CommandType = System.Data.CommandType.Text;
//Do something for fill comand.Parameters from MyDinamicSql...
I want a way to get a parameter collection with [#Param1,#Param2]... I don't know the sql queries (they are dynamic) and I want to get the parameters for my application to create them as input controls.
I can't do this with SqlCommandBuilder.DeriveParameters(command), because it only works with stored procedures.
Thank you!

No - until SQL Server parses the command, it's just a string.

Related

Getting "The SqlParameter is already contained by another SqlParameterCollection." error while using SqlQuery command

I am trying to parameterize a dynamic query and run it using SqlQuery method in Entity Framework code first.
The first time I execute SqlQuery it works as expected so I am sure there is nothing wrong with query or parameters but immediately I execute the same command with the same parameters second time and I get this error
"The SqlParameter is already contained by another SqlParameterCollection."
Since I am already using ToList() method here, I have no idea what the cause could be!
Here is the simulated code.
using (var context = Common.GetDbContext())
{
var parameters = new List<SqlParameter>();
//populating parameters here...
var sqlQuery = "Select * from MyTable where UserId=#p1 and And Active=#p2";
// first time
var result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.ToArray()).ToList();
//second time
result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.ToArray()).ToList();
}
Any idea?
Hi SqlParameter is clonable. Try this:
result = context.Database.SqlQuery<ResultType>(sqlQuery, parameters.Select(x => x.Clone()).ToArray()).ToList();
See https://msdn.microsoft.com/en-us/library/vstudio/bb338957%28v=vs.100%29.aspx

VB Script in Access Variable not found

So I was advised that I could create some copy replace functionality to this form.
Here is my coding attempt in VB:
First I connect to DB using DAO. Then I use a SELECT statement that has been verified to pull the last record inserted into the DB. Then I try to refill the controls with the values from the query but I am getting reference errors.
Private Sub AutoFill_Click()
Dim db As DAO.Database, rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb()
strSQL = "SELECT DISTINCTROW TOP 1 CPOrders.Cust, Customer.NAME, CPOrders.CP_Ref, CPOrders.Slsman, CPOrders.Date_opn, CPOrders.CPSmall, CPOrders.InvIssu, CPOrders.InvNo, CPOrders.InvDate, CPOrders.DueDate, CPOrders.ETADate, CPOrders.Closed, CPOrders.BuyerRef, CPOrders.ToCity, CPOrders.ToState, CPOrders.ToCtry, CPOrders.ToPort, CPOrders.Supplier, CPOrders.Origin, CPOrders.Product, CPOrders.GradeType, CPOrders.NoUnits, CPOrders.Pkg, CPOrders.Qty, CPOrders.TotSale, CPOrders.TotCost, CPOrders.GrMargin, CPOrders.[Sale$/Unit], CPOrders.[Cost$/Unit], CPOrders.OceanCost, CPOrders.OceanNotes, CPOrders.BLadingDate, CPOrders.USAPort, CPOrders.FOBCost, CPOrders.FASExportVal, CPOrders.InlandFrt, CPOrders.CommodCode, CPOrders.Notes FROM Customer INNER JOIN CPOrders ON Customer.[CUST_#] = CPOrders.Cust ORDER BY CPOrders.CP_Ref desc;"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
rs.MoveFirst
CP_Ref.ControlSource = rs!CP_Ref
Slsman.ControlSource = rs!Slsman
CPSmall.ControlSource = rs!CPSmall
InvIssu.ControlSource = rs!InvIssu
InvDate.ControlSource = rs!InvDate
DueDate.ControlSource = rs!DueDate
Closed.ControlSource = rs!Closed
rs.Close
db.Close
The control source reference picks up and autocompletes the word.
I would think that as it stands. although i'm not filling all the values with records from my SELECT statement that it would populate but instead i get things like #NAME? where the values should be. I also get a break in my code and it says "Invalid use of null"
Why? I appreciate your guys input and I can provider screenshots if necessary. I think this is involving the reference tie, but I'm not sure. Any help is much appreciated.
You are using the field names from the SELECT statement as if they were variables.
CP_Ref.ControlSource = rs("CP_Ref")
Slsman.ControlSource = rs("Slsman")
CPSmall.ControlSource = rs("CPSmall")
InvIssu.ControlSource = rs("InvIssu")
InvDate.ControlSource = rs("InvDate")
DueDate.ControlSource = rs("DueDate")
Closed.ControlSource = rs("Closed")
When you have that worked out, tackle the "Invalid use of null" problem by first identifying any fields that could potentially be NULL and using something like
SELECT Iif(IsNull([InvDate]), '', [InvDate]) As [InvDate], ...
in the SELECT statement to pass across a minimum of an empty string rather than a NULL value.

Where is my num_rows failing?

<?php
$link = mysqli_connect('localhost','root','root');
$link->query('CREATE DATABASE IF NOT EXISTS users');
$link->Select_db('users');
$sql='SELECT id FROM users WHERE email = '.$useremail.' AND username = '.$username;
$results = $link->query($sql);
$numrows = $results->num_rows;
if ($numrows == 1) {
#update user information
} else {
#failed to update
}
?>
It only works part of the time, and i'm not able to nail down an error from it one way or the other. I can confirm that the error pops up on the $numrows=$results->num_rows; line, but as for why, i'm lost. Occasionally it will work as intended, so any and all advice on what i can do to fix it, or at least helping me understand it better is greatly appreciated. Thanks!
Use Double Quotation for query and varchar/string pass with single quotation
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$results = $link->query($sql);
$numrows = $results->num_rows();
The reason that your call to num_rows generated an error is that your query had an error, and query() returned false instead of a valid result resource. Because it's a fatal error to try to call a method on a false value, you should always check the return value of query() before using it. Example:
if (!($result = $link->query($sql))) {
die($link->error);
}
Problems with your query:
You create a database named users and make that the default database, then you run a SELECT query from a table named users. There would be no tables in a database you have just created. In SQL, we use SELECT against tables, not databases (these are two different things, analogous to files contained in a directory on a filesystem).
You don't quote the string arguments in your SQL statement. For example, this SQL would be an error:
SELECT id FROM users WHERE email = bill#example.com AND username = bill
It should be this instead:
SELECT id FROM users WHERE email = 'bill#example.com' AND username = 'bill'
I know the quotes get confusing, because you have PHP string quotes and then SQL string quotes, but here are several ways of accomplishing it:
$sql='SELECT id FROM users WHERE email = \''.$useremail.'\' AND username = \''.$username.'\'';
$sql="SELECT id FROM users WHERE email = '".$useremail."' AND username = '".$username."'";
$sql="SELECT id FROM users WHERE email = '{$useremail}' AND username = '{$username}'";
I'm not sure if you have protected your PHP variables appropriately. You must never interpolate PHP variables into SQL strings unless you have escaped the content of the variables.
$useremail_esc = $link->real_escape_string($useremail);
$username_esc = $link->real_escape_string($username);
$sql="SELECT id FROM users WHERE email = '{$useremail_esc}' AND username = '{$username_esc}'";
But it would be better to use prepared statements with parameter placeholders. This is easier to use than escaping variables, and it's more reliable. Here's an example:
$sql="SELECT id FROM users WHERE email = ? AND username = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $useremail, $username);
$stmt->execute();
$result = $stmt->get_result();
Notice that you don't use escaping when you use parameters, and you don't put SQL quotes around the ? placeholders.

iDB2Commands in Visual Studio 2010

These are the basic things I know about iDB2Commands to be used in Visual Studio 2010. Could you please help me how could I extract data from DB2? I know INSERT, DELETE and Record Count. But SELECT or Extract Data and UPDATE I don't know.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
'*****Delete Records and working fine
sqlUpdate = "DELETE FROM expusers WHERE username<>#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2Date)
cmdUpdate.Parameters("username").Value = ""
'*****Insert Records and working fine
sqlUpdate = "INSERT INTO expusers (username, password, fullname) VALUES (#username, #password, #fullname)"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("fullname", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Parameters("fullname").Value = "Editha D. Gacusana"
'*****Count Total Records and working fine
Dim sqlCount As String
Dim cmd As New iDB2Command
sqlCount = "SELECT COUNT(*) AS count FROM import"
cmd = New iDB2Command(Sql, conn)
Dim count As Integer
count = Convert.ToInt32(cmd.ExecuteScalar)
'*****Update Records and IT IS NOT WORKING AT ALL
sqlUpdate = "UPDATE expusers SET password = #password WHERE RECNO = #recno"
cmdUpdate.Parameters.Add("recno", iDB2DbType.iDB2Integer)
cmdUpdate.Parameters.Add("password", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters("recno").Value = 61
cmdUpdate.Parameters("password").Value = txtPassword.Text
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me how to code the SELECT query wherein I could extract/fetch data from DB2 Database. Also, how could i update the records in the database.
Thanks!
Instead of ExecuteNonQuery(), look at ExecuteReader(). I don't have VS2010 installed, but try something like this:
iDB2Command cmdSelect = new iDB2Command("SELECT username, password, fullname FROM expusers", conn);
cmdSelect.CommandTimeout = 0;
iDB2DataAdapter da = new iDB2DataAdapter(cmdSelect);
DataSet ds = new DataSet();
da.Fill(ds, "item_master");
GridView1.DataSource = ds.Tables["expusers"];
GridView1.DataBind();
Session["TaskTable"] = ds.Tables["expusers"];
da.Dispose();
cmdSelect.Dispose();
cn.Close();
See: http://gugiaji.wordpress.com/2011/12/29/connect-asp-net-to-db2-udb-for-iseries/
If you aren't trying to bind to a grid, look at iDB2Command.ExecuteReader() and iDB2DataReader()
The DELETE is working fine? The code has the parameter type for "username" set to iDB2Date. The INSERT has "username" set to iDB2VarChar. How is the column defined in the table? Char, Varchar or Date?
On the UPDATE, you reference RECNO, but that does not seem to be a column in the table. Updating a relational database table by row number is a bad idea - the row numbers are not guaranteed to stay constant. If you are just testing, as I think you are, don't use RECNO, use RRN(). The DB2 for i syntax is WHERE rrn(expusers) = #recno
To help your testing, do a SELECT without a WHERE clause and list out all the rows. Make sure the name stored in the username column matches the name you are trying to update. Pay particular attention to the case of the data. If the name in expusers looks like "EDITHA D. GACUSANA", and #username is "Editha D. Gacusana" then it will not match on the WHERE clause.

Can I use SQLParameter when having a variable quantity of fields to update?

I have a table with eighty fields, none to seventy of them can change depending of an update process I have. For example:
if (process.result == 1)
cmd.CommandText = "UPDATE T SET f1=1, f6='S'" ;
else if (Process.result == 2)
cmd.CommandText = string.Format("UPDATE T SET f1=2, f12={0},f70='{1}'", getData(), st);
else if ..... etc.
I can optimize the building process of the UPDATE statement, however I would like to use SQLParameter; is that possible and convenient given the variablity of data to update?
Thanks.
For each if statement you currently are using inline string formats, you could just as well just add the sql params instead.
The formatting of the UPDATE string could be replaced with the selected sql params you require to be updated insted.