In my symfony 3 project i got a entity to log changes.
To save the changes I'm using two serialized arrays with the old and the new objects.
Log-Class:
/*
* #ORM\Column(name="oldData", type="blob", nullable=false)
*
* #Serializer\Expose
*/
private $oldData;
/**
* Set oldData
*
* #param $Data
*/
public function setOldData( $data )
{
$this->oldData = serialize( $data );
return $this;
}
I'm using this class in another controller:
$log = new ChangeLog();
$log->setUser( $this->getUser() );
$log->setOfferBase( $ConditionSet->getOfferbaseId() );
$log->setOldData( $ConditionSet );
After i saved the new object im using following code to save the new changes in the log:
$log->setNewData( $ConditionSet );
$em->persist( $log );
$em->flush();
The problem is that the datas aren't saved in the database and i got a 0 byte blob. I doesn't get any error but in my log I saw that symfony didn't tried to save the data:
doctrine.DEBUG: INSERT INTO changeLog (changeDate, offerBase, user) VALUES (?, ?, ?) {"1":"2016-08-09 17:28:39","2":45,"3":1} []
I tried the following to catch the exception. But output is "No exception".
try {
$em->persist( $log );
$em->flush();
$message = "No exception";
} catch (DBALException $e) {
$message = sprintf('DBALException [%i]: %s', $e->getCode(), $e->getMessage());
} catch (PDOException $e) {
$message = sprintf('PDOException [%i]: %s', $e->getCode(), $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException [%i]: %s', $e->getCode(), $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception [%i]: %s', $e->getCode(), $e->getMessage());
}
return new Response($message);
Related
i have the following code (assume transaction is working properly)
try{
if (!$model->save() {
$return = Yii::t('app/job', 'JOB_NOT_FOUND');
trow new \Exception();
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $return);
}
i receiver php error undefined variable return
Any effort is highly appreciated
return is a PHP keyword and could lead to confusion.
Are you using PHP 5.x? PHP keywords are allowed since PHP 7.0.0
Try this:
try{
if (!$model->save() {
throw new \Exception(Yii::t('app/job', 'JOB_NOT_FOUND'));
}
} catch(Exception $e) {
$transaction->rollBack();
return (new ApiResponse)->error(null, ApiResponse::EXPECTATION_FAILED, $e->getMessage());
}
So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}
How can i check the availability of Redis connection in Laravel 5.4. I tried below code, but getting an exception with ping line. How can i do, if Redis is not connected than do something else to avoid exception?
No connection could be made because the target machine actively
refused it. [tcp://127.0.0.1:6379]
use Redis;
class SocketController extends Controller
{
public function sendMessage(){
$redis = Redis::connection();
if($redis->ping()){
print_r("expression");
}
else{
print_r("expression2");
}
}
}
Also tried this:
$redis = Redis::connection();
try{
$redis->ping();
} catch (Exception $e){
$e->getMessage();
}
But unable to catch exception
if you are using predis , then it will throw Predis\Connection\ConnectionException
Error while reading line from the server. [tcp://127.0.0.1:6379] <--when redis is not connected
so catch that Exception, you will get your redis is connected or not .
use Illuminate\Support\Facades\Redis;
public function redis_test(Request $request){
try{
$redis=Redis::connect('127.0.0.1',3306);
return response('redis working');
}catch(\Predis\Connection\ConnectionException $e){
return response('error connection redis');
}
<?php
namespace App\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
class ConnectionChecker
{
public static function isDatabaseReady($connection = null)
{
$isReady = true;
try {
DB::connection($connection)->getPdo();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
public static function isRedisReady($connection = null)
{
$isReady = true;
try {
$redis = Redis::connection($connection);
$redis->connect();
$redis->disconnect();
} catch (\Exception $e) {
$isReady = false;
}
return $isReady;
}
}
I created a helper class to check redis and db connection
Make sure redis is installed
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
To test that your service is functioning correctly, connect to the Redis server with the command-line client:
redis-cli
In the prompt that follows, test connectivity by typing:
ping
You should see:
Output
PONG
Install Laravel dependencies
composer require predis/predis
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04
https://askubuntu.com/questions/868848/how-to-install-redis-on-ubuntu-16-04
In your constructor you can check redis status connection like this:
/**
* RedisDirectGeoProximity constructor.
* #throws RedisConnectionException
*/
public function __construct()
{
try
{
$this->redisConnection = Redis::connection('default');
}
catch ( Exception $e )
{
throw new RedisConnectionException([
'message' => trans('messages.redis.fail'),
'code' => ApiErrorCodes::REDIS_CONNECTION_FAIL
]);
}
}
and in your exception :
namespace App\Exceptions\Redis;
/**
* Class RedisConnectionException
* #package App\Exceptions\Redis
*/
class RedisConnectionException extends \Exception
{
/**
* RedisConnectionException constructor.
* #param array $options
*/
public function __construct(array $options = [])
{
parent::__construct($options);
}
}
please try with catch (\Exception $e) incl. backslash
I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}
I suffering the same problem on the link BigQuery [PHP] InsertAll Error: No records present in table data append request. I followed the solution, error was removed but result is not affected on the BigQuery table my code is:
$data = '{"rows":[{"json":{"userId":"GR-003","state":"Pune","sales":"350"}}]}';
$data1 = json_decode($data);
try{
$rows = array();
$row = new Google_Service_Bigquery_TableDataInsertAllRequestRows;
$row->setJson($data1);
$row->setInsertId('9');
$rows[0] = $row;
$request = new Google_Service_Bigquery_TableDataInsertAllRequest;
$request->setKind('bigquery#tableDataInsertAllRequest');
$request->setRows($rows);
$service->tabledata->insertAll(PROJECT_ID, DATASET_ID , 'sample_table', $request);
} catch (Exception $e)
{
echo $e->getMessage();
}
You are sending the wrong object to big query. Change the $data to an object, and make sure you don't have rows and json level, also make sure variable type is correct as BigQuery is very strict, like string, string, integer or float if you have it.
$rows = array();
foreach() {
$obj = new StdClass();
$obj->userId='GR-003';
$obj->state='Pune';
$obj->sales=350;
$row = new Google_Service_Bigquery_TableDataInsertAllRequestRows;
$row->setJson($obj);
$row->setInsertId('9');
$rows[] = $row;
}