How do I do error checking, in my model? For instance if my procedure adds a record I want to return true if not I want to return false. Do I need to do a count on the records in the table before and after the procedure then compare them which is the best way to do this?
function add_student($SECTION_ID, $STUDENT_ID)
{
$this->db->query("call add_student('$SECTION_ID','$STUDENT_ID')");
}
function drop_student($SECTION_ID, $STUDENT_ID)
{
$this->db->query("call drop_student('$SECTION_ID','$STUDENT_ID')");
}
Looks like your database is mysql
Use FOUND_ROWS( ) to find rows affected after executing the select statement in the procedure
Or You could use ROW_COUNT() function to find the number of records after insert statement
Related
When I execute a SQL query from Java and store the boolean returned, the query always returns true which shouldn't be the case at all. So I emptied the table and fired the query again, and yet it returns true for the emptied table. I have attached a picture of the table. I want the query to return true or false, so I can store it in Java. Can someone please specify an alternate code for this, please?
This is my code on java for the query.
boolean avail = st.execute("SELECT EXISTS(SELECT * from sales WHERE product='"+n+"' AND ord_date='"+sqlDate+"');");
And this is my code for result set
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
This is the table, name of the table is 'sales'
I'm new to MySQL, a more specific approach is appreciated.
Statement.execute will return true regardless of what the query returns. You are still supposed to retrieve the actual result of the query.
Returns
true if the first result is a ResultSet object; false if it is an update count or there are no results
As you execute an EXISTS statement, there will always be a result (true or false). The actual value still has to be retrieved:
You must then use the methods getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s).
For reference: https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#execute-java.lang.String-String
Also note that you are directly embedding strings into your query, this will leave you vulnerable to SQL injections. Please read: How can prepared statements protect from SQL injection attacks?. Recommended reading: Introduction to JDBC
The return value of Statement.execute() signals whether the query produces a result set (true) or - possibly - an update count (false). The query you execute is a select which will always produce a result set (even if empty). In other words, it will always return true for a select.
If you want to get the result of your query, then the recommend approach is to use executeQuery. However, you are also concatenating values into your query string, which is a bad idea because it leave you vulnerable to SQL injection. The recommended approach is to switch to prepared statements:
try (PreparedStatement pstmt = con.prepareStatement(
"SELECT EXISTS(SELECT * from sales WHERE product = ? AND ord_date = ?)")) {
pstmt.setString(1, n);
pstmt.setDate(2, sqlDate);
try (ResultSet rs = st.executeQuery() {
boolean avail = rs.next() && rs.getBoolean(1);
// use avail...
}
}
I am trying to call a stored procedure from code , in ef core 2 i found that i can use context.database.ExecuteSqlCommand() function to execute any stored procedure in my database.
While the stored procedure works fine in my sql server instance :
calling it from my code , returns -1 result !?:
using (var context = new AZPDBDEMOGZContext(optionsBuilder.Options))
{
var existUser = context.Database.ExecuteSqlCommand("GetIdUsager_ByNomPrenomEmail #p0,#p1,#p2", parameters:new[] { "rouarouarouarouaroua", "wiem", "test#gmail.com" });
}
what m i doping wrong ?
ExecuteSqlCommand will only return a 'rows affected' integer for a DML query aka insert/update/delete. Your stored proc looks like its returning a result set so it returns -1 as you've not provided a statement that changes the data source. You'll need to create a POCO and use FromSql to populate it.
I am having trouble finding the correct syntax to execute multiple MySQL statements at once, like with cftransaction. I'm trying to implement this in a CFC in pure cfscript.
<cftransaction>
DROP TABLE IF EXISTS SOME_TEMP_TBL;
CREATE TABLE SOME_TEMP_TBL AS
(
SELECT * FROM ANOTHER_TBL
);
DROP TABLE IF EXISTS SOME_TEMP_TBL_2;
CREATE TABLE SOME_TEMP_TBL_2 AS
(
SELECT * FROM ANOTHER_TBL_2
);
</cftransaction>
So I have the SQL statements chained together as a string:
var SQL = "
DROP TABLE IF EXISTS SOME_TEMP_TBL;
CREATE TABLE SOME_TEMP_TBL AS
(
SELECT * FROM ANOTHER_TBL
);
DROP TABLE IF EXISTS SOME_TEMP_TBL_2;
CREATE TABLE SOME_TEMP_TBL_2 AS
(
SELECT * FROM ANOTHER_TBL_2
);
";
And if I understand right I think I need to use a transaction {} block. But do I put raw MySQL code in there? Currently I'm trying to attach it to a Query object but Base.cfc (Railo) is throwing an error saying the datasource isn't defined.
transaction
{
qTrans = new Query();
qTrans.setSQL(SQL);
qTrans.execute();
qTrans.setDatasource(variables.instance.datasource.getDSN());
if (good)
{
transaction action="commit";
} else {
transaction action="rollback";
}
}
Have also tried just SQL.execute() but of course execute() isn't defined for a string & it wouldn't relate to any DB anyway...
Also, is the if(good) portion required? By default does if(good) test for whether or not a MySQL error occurred? And is transaction action="commit" what actually sends the SQL script?
Do I need to split these up into separate Query objects and run them sequentially? And if so what's the point of even having the transaction block in CFscript?
I know I'm way off here but I'm having a hard time navigating the CF documentation around this. If anyone knows of a good source specifically for CFscript references I could really use one, because I struggle with Adobe's version.
Try this code
try {
transaction {
qTrans = new Query();
qTrans.setDatasource(variables.instance.datasource.getDSN());
qTrans.setSQL(SQL);
qryRes = qTrans.execute();
TransactionCommit();
}
} catch(database e) {
TransactionRollback();
}
I have a function written in PL/pgSQL which is mentioned here:
CREATE OR REPLACE FUNCTION test()
RETURNS SETOF ccdb.consumers AS
$body$
BEGIN
RETURN QUERY
SELECT consumers.* FROM ccdb.consumers JOIN ccdb.consumer_index_details USING (cin) LIMIT 10;
END;
$body$
LANGUAGE plpgsql;
When I give consumers.* in the select statement then the function executes perfectly. But when I try to get the fields also from my consumer_index_details table then I get an error saying,
ERROR: structure of query does not match function result type
DETAIL: Returned type character varying(30) does not match expected type numeric(13,0) in column 2.
CONTEXT: PL/pgSQL function test() line 5 at RETURN QUERY
Here what I understood by the error is that since in my return type I have given consumers table, it is expecting the output structure to be the same. So my question is, what should be the RETURN TYPE if I want to get the fields from multiple tables, the return could be dynamic?
You can try using RETURNS TABLE() with the list of columns as your table definition...
Hope it works out for you..
I'm using sqljocky to insert data into a MySQL database. I need to truncate a table first, then insert multiple rows in it. I would do this in a single transaction, but it seems that sqljocky doesn't support this at all now (or maybe I'm quite new in dart and sqljocky).
The solution I found is the following, but I was wondering if there's a better one.
// Start transaction
pool.query('START TRANSACTION').then((r) {
// Truncate table
pool.query('TRUNCATE myTable').then((r) {
// Prepare statement to insert new data
pool.prepare('REPLACE INTO myTable (Id, Name, Description) VALUES (?,?,?)').then((query) {
// Execute query inserting multiple rows
query.executeMulti(myArrayValues).then((results) {
// Other stuff here
pool.query('COMMIT').then((r) {
...
To be honest, I'm still wondering if this code really executes a transactioned query!
Here's the same code rewritten with transaction support:
// Start transaction
pool.startTransaction().then((trans) {
// Delete all from table
trans.query('DELETE FROM myTable WHERE 1=1').then((r) {
// Prepare statement
trans.prepare('REPLACE INTO myTable (Id, Name, Description) VALUES (?,?,?)').then((query) {
// Execute query inserting multiple rows
query.executeMulti(myArrayValues).then((results) {
// Stuff here
// Commit
trans.commit().then((r) { ...
Use ConectionPool.startTransaction().
* You
* must use this method rather than `query('start transaction')` otherwise
* subsequent queries may get executed on other connections which are not
* in the transaction.
Haven't tried it myself yet.