Cannot create parameterised query for Interbase using ADO.NET - ado.net

I'm trying to issue a parameterised SELECT to an Interbase XE database using ADO.NET. The code I'm using is as follows:
using (OdbcConnection odbcConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["LawbaseTest"].ToString()))
{
odbcConnection.Open();
using (OdbcCommand odbcCommand = new OdbcCommand())
{
odbcCommand.CommandType = CommandType.Text;
odbcCommand.Connection = odbcConnection;
odbcCommand.Parameters.Add(new OdbcParameter(":CaseNumber", 1265));
odbcCommand.CommandText = "select * from cmstub where cm_recnum = :CaseNumber";
using (IDataReader rdrData = odbcCommand.ExecuteReader())
{
Output(rdrData["CM_DESC"]);
}
}
}
I'm getting the following error:
ERROR [42S22] [DataDirect][ODBC InterBase driver][InterBase]Dynamic SQL Error, SQL error code = -206, Column unknown, CASENUMBER
Which suggests to me that the query is not being sent to Interbase in a syntax it recognises as a parameterised query.
This is rather harder than I was expecting. Am I being a ficko? Can you help?

It seems to be the norm that named parameters aren't supported widely, did you try using ? instead, i.e. cm_recnum = :CaseNumber to cm_recnum = ?

Related

Linq2db.EntityFrameworkCore against Oracle

I don't understand why linq2db is not generating the correct SQL string for this query against Oracle, and it is working perfectly against SQLServer.
string idUser="U1";
await context.Users.ToLinqToDbTable().Where(u=>u.IdUser == idUser).FirstOrDefaultAsyncLinqToDB();
Always returns null. However, it works if el value used directly:
await context.Users.ToLinqToDbTable().Where(u=>u.IdUser == "U1").FirstOrDefaultAsyncLinqToDB();
Looking at the logs, el SQL statement generated is like this:
-- Oracle Oracle11
DECLARE #idUser Varchar2(8) -- String
SET #idUser = 'U1'
SELECT
u.IdUser,
etc..
FROM
USERS u
WHERE
u.IDUSER = :idUser
Why is it generating T-SQL code and not Oracle code (the context is initialized with .UseOracle())?
Thanks

Postgres Aliasing [duplicate]

I have been able to link PostgreSQL to java. I have been able to display all the records in the table, however I unable to perform delete operation.
Here is my code:
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE MAC = 'kzhdf'";
pst = con.prepareStatement(stm);
pst.executeUpdate();
Please note that MAC is a string field and is written in capital letters. This field does exist in the table.
The error that I am getting:
SEVERE: ERROR: column "mac" does not exist
When it comes to Postgresql and entity names (Tables, Columns, etc.) with UPPER CASE letters, you need to "escape" the word by placing it in "". Please refer to the documentation on this particular subject. So, your example would be written like this:
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = 'kzhdf'";
On a side note, considering you are using prepared statements, you should not be setting the value directly in your SQL statement.
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = ?";
pst = con.prepareStatement(stm);
pst.setString(1, "kzhdf");
pst.executeUpdate();

Querying average with a function of column in Rails

I'm using Rails 4 in a web app, Postgresql database and squeel gem for queries.
I have this function in my model statistic.rb
def properties_mean_ppm(mode, rooms, type, output_currency_id)
sql_result = properties(mode, rooms, type).select{
avg(price_dolar / property_area).as(prom)
}
avg = sql_result[0].prom
final_avg = change_currency(avg, DOLAR_ID, output_currency_id)
return final_avg.to_f
end
price_dolar and property_area are columns in the properties table.
It works fine in Rails console and displays the result, but when I use it on the controller it gives an error:
ActiveModel::MissingAttributeError (missing attribute: id)
And indicates the line
avg = sql_result.to_a[0].prom
I also tried using sql_result[0].prom or sql_result.take or sql_result.first, they all have the same error.
The sql_result is this:
#<ActiveRecord::Relation [#<Property >]>
This is the action called in the controller
def properties_mean_ppm
#statistic = Statistic.find(params[:id])
mode = params[:mode] ? params[:mode] : ANY_MODE
type = params[:type] ? params[:type] : ANY_TYPE
one_room = #statistic.properties_mean_ppm(mode, 1, type, UF)
end
I know how to get the result using only SQL without activerecord but that would be very inefficient for me because I have lots of filters called before in the properties() function
Seems like calling that from the properties object made the controller to expect a Property with an id as a result. So I made it work without squeel.
sql_result = properties(mode, rooms, type).select(
"avg(precio_dolar / dimension_propiedad) as prom, 1 as id"
)
And giving a fixed id to the result

Entity Framework Stored Procedure with Multiple Record Set not accepting my parameter

I'm using Microsofts suggested solution for using Entity Framework to read multiple record sets from a stored procedure but added a small snippet to use parameters and it's not working. I've had a co-worker look at the code and tell me it looks like it should work so I thought I'd ask here.
Using the 4.5 framework is not an option. I'm stuck with 4.0 and etity framework 4.4.
App MyApp = (App)Application.Current;
EnterpriseEntities EE = new EnterpriseEntities();
EE.Database.Connection.ConnectionString = MyApp.EnterpriseEntityConnectionString;
var cmd = EE.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[spSelectWaterUsesByRightID]";
var param = cmd.CreateParameter();
param.Direction = ParameterDirection.Input;
param.DbType = DbType.Int32;
param.ParameterName = "#RightID";
param.Value = this.RightID;
cmd.Parameters.Add(param);
EE.Database.Connection.Open();
var reader = cmd.ExecuteReader();
List<WaterUses> ListOfWaterUses = (((System.Data.Entity.Infrastructure.IObjectContextAdapter)EE)
.ObjectContext
.Translate<WaterUses>(reader, "WaterUses",System.Data.Objects.MergeOption.AppendOnly)).ToList();
When I get to the ExecuteReader line I get an error message that the stored procedure requires Parameter #RightID but that's what I'm passing. I checked the parameter count right before it executes and it's at 1.
You have to add
cmd.CommandType = CommandType.StoredProcedure;
somewhere before cmd.ExecuteReader().

zend framework 1.11.5 is choking on search function - mysql db

ZF 1.11.5 is puking all over this search function. i've tried creating the query several different ways, sent the sql statement to my view, copied and pasted the sql statement into phpMyAdmin and successfully retrieved records using the sql that ZF is choking on. i have been getting a coupld of different errors: 1) an odd SQL error about 'ordinality' (from my Googling ... it seems this is a ZF hang up .. maybe?) and 2) Fatal error: Call to undefined method Application_Model_DbTable_Blah::query() in /blah/blah/blah.php on line blah
public function searchAction($page=1)
{
$searchForm = new Application_Model_FormIndexSearch();
$this->view->searchForm = $searchForm;
$this->view->postValid = '<p>Enter keywords to search the course listings</p>';
$searchTerm = trim( $this->_request->getPost('keywords') );
$searchDb = new Application_Model_DbTable_Ceres();
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$selectQuery = $searchDb->query($selectSql);
$searchResults = $selectQuery->fetchAll();
}
here's my model ....
class Application_Model_DbTable_Ceres extends Zend_Db_Table_Abstract
{
protected $_name = 'listings';
function getCourse( $courseId )
{
$courseid = (int)$courseId;
$row = $this->fetchRow('id=?',$courseId);
if (!$row)
throw new Exception('That course id was not found');
return $row->toArray();
}
}
never mind the view file ... that never throws an error. on a side note: i'm seriously considering kicking ZF to the curb and using CodeIgniter instead.
looking forward to reading your thoughts. thanks ( in advance ) for your responses
You're trying to all a method called query() on Zend_Db_Table but no such method exists. Since you have built the SQL already you might find it easier to call the query on the DB adapter directly, so:
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$searchResults = $selectQuery->getAdapter()->fetchAll($selectSql);
but note that this will give you arrays of data in the result instead of objects which you might be expecting. You also need to escape $searchTerm here since you are getting that value directly from POST data.
Alternatively, you could form the query programatically, something like:
$searchTerm = '%'.$searchTerm.'%';
$select = $selectQuery->select();
$select->where('s_coursedesc LIKE ?', $searchTerm)
->orWhere('s_title LIKE ?', $searchTerm);
$searchResults = $searchQuery->fetchAll($select);