how do you programmatically tell whether a mysql connection is present? - mysql-real-escape-string

I get this error when I run mysql_real_escape_string($value).
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to MySQL server on 'localhost' (10061) in ...
I wrapped up the functionality in a nice class like this
class escaper
{
function __get($value)
{
//in order for this to work properly, I must have a live connection to mysql
return mysql_real_escape_string($value);
}
}
/*
//sample usage
$safe = new escaper;
$name = "O'Reilly";
echo $safe->$name
In case someone goes down that road again, let me say it upfront that Yes! I should use PDO and parametrized queries and that the above method is not that safe.

how do you programmatically tell whether a mysql connection is present?
we just don't need that.
connection is always present
Escaping being a part of the DB class.
Connect to the database is the very first thing this class doing in the constructor.
And connect resource stored in the class variable.
So, only we need is to use this variable - easy-peasy.

Related

How to get GraphDatabaseService instance from Bolt Driver

I wrote some codes that used java Api of GraphDatabaseService to access an embedded database before. But now I want to switch the database to a remote one, so I have to use Driver and Session class to write and run cyphers. I don't like cyphers and I don't want to change the old codes.
So I'm looking for a way so that I can get GraphDatabaseService from Driver, but none is found.
I think a possible way is to make up a GraphDataBaseService delegate that wraps a Driver and converts Api calls to cyphers. Is that feasible? Is there already some libraries which can do this?
You won't get a direct equivalent of GraphDatabaseService since that's the embedded API.
You can however run Cypher queries like this:
var driver = GraphDatabase.driver(
"some://address",
AuthTokens.basic("username", "password")
);
// [...]
try (var session = driver.session() {
return session.writeTransaction(tx -> {
Result result = tx.run(
"CYPHER QUERY",
Map.of(/* query parameters */)
);
// do something with result
});
}
// [...]
driver.close(); // (driver is usually a singleton - closes when application shuts down)
I tried to make a project to solve this problem by wrapping Driver to GraphDatabaseService.

MongoDB Secondary Replica does not show databases - code "NotMasterNoSlaveOk" [duplicate]

I tried mongo replica sets for the first time.
I am using ubuntu on ec2 and I booted up three instances.
I used the private IP address of each of the instances. I picked on as the primary and below is the code.
mongo --host Private IP Address
rs.initiate()
rs.add(“Private IP Address”)
rs.addArb(“Private IP Address”)
All at this point is fine. When I go to the http://ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:28017/_replSet site I see that I have a primary, seconday, and arbitor.
Ok, now for a test.
On the primary create a database in this is the code:
use tt
db.tt.save( { a : 123 } )
on the secondary, I then do this and get the below error:
db.tt.find()
error: { "$err" : "not master and slaveOk=false", "code" : 13435 }
I am very new to mongodb and replicates but I thought that if I do something in one, it goes to the other. So, if I add a record in one, what do I have to do to replicate across machines?
You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:
rs.secondaryOk()
After that you can query normally from secondaries.
A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.
Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.
To avoid typing rs.slaveOk() every time, do this:
Create a file named replStart.js, containing one line: rs.slaveOk()
Then include --shell replStart.js when you launch the Mongo shell. Of course, if you're connecting locally to a single instance, this doesn't save any typing.
in mongodb2.0
you should type
rs.slaveOk()
in secondary mongod node
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
WARNING: slaveOk() is deprecated and may be removed in the next major release. Please use secondaryOk() instead. rs.secondaryOk()
I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.
The issue is that readPreference setting defaults to primary, which then somehow leads to the confusing slaveOk error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.
Setting readPreference to primaryPreferred (or better to the ReadPreference.PRIMARY_PREFERRED constant) solved it for me. Just pass it as an option to MongoClient.connect() or to client.db() or to any find(), aggregate() or other function.
https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred
http://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html (search readPreference)
const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
slaveOk does not work anymore. One needs to use readPreference https://docs.mongodb.com/v3.0/reference/read-preference/#primaryPreferred
e.g.
const client = new MongoClient(mongoURL + "?readPreference=primaryPreferred", { useUnifiedTopology: true, useNewUrlParser: true });
I am just adding this answer for an awkward situation from DB provider.
what happened in our case is the primary and secondary db shifted reversely (primary to secondary and vice versa) and we are getting the same error.
so please check in the configuration settings for database status which may help you.
Adding readPreference as PRIMARY
const { MongoClient, ReadPreference } = require('mongodb');
const client = new MongoClient(url, { readPreference: ReadPreference.PRIMARY_PREFERRED});
client.connect();

DB connection is not closed after request ends in a NancyFx application

I'm building a Nancy web app, and using OrmLite for DB access. I noticed that every request opens up a new DB connection and doesn't close it. I thought that registering the OrmLiteConnection class in the Application container would make it application-scoped, but it looks like I'm missing something.
Here's my code (in ConfigureApplicationContainer):
container.Register<OrmLiteConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
container.Register<OrmLiteConnection>(
(cContainer, overloads) => (OrmLiteConnection) cContainer.Resolve<OrmLiteConnectionFactory>().Open());
You need to add scope to your registration(s):
container
.Register<OrmLiteConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider))
.AsSingleton(); // I think this is by default, but sometimes being explicit is good.
container
.Register<OrmLiteConnection>(
(cContainer, overloads) => (OrmLiteConnection) cContainer.Resolve<OrmLiteConnectionFactory>().Open())
.AsPerRequestSingleton();;
AFAIK, this will ensure the instances are disposed at the scope's end. Therefore, if you need to do more than Dispose() then you might need to find some way of supplying a delegate that can executed at that time.
I moved registration of OrmLiteConnection to ConfigureRequestContainer. Then I overrode RequestStartup and added:
pipelines.AfterRequest += (ctx) => {
//close the connection
container.Resolve<OrmLiteConnection>().Dispose();
};

How to call mysql stored procedure with dynamic name in grails

I have requirement like to call the stored procedures to get the data, here i will get the stored procedure name through post data.
I tried using GString but no use, Can any one help me to solve this issue.
Thanks in advance.
This is a weird one, but possible. Grails/GORM doesn't provide a way to execute stored procedures. It's just not part of ORM functionality. And neither does Hibernate. But, Hibernate does provide access to a JDBC connection. So you can get a connection from Hibernate, then create a Groovy Sql instance with the connection, and finally execute your stored procedure. Here's an example:
import groovy.sql.Sql
SomeDomainClass.withNewSession { session ->
session.doWork { java.sql.Connection connection ->
def sql = new Sql(connection)
sql.call("YOUR STORED PROCEDURE SQL HERE")
}
}
It works like this:
Using any of your domain classes, call withSession(Closure) to get a Hibernate session.
With the session, call doWork(Work) to get access to the session's JDBC connection. Now, doWork(Work) expects an implementation of org.hibernate.jdbc.Work. But, if I recall correctly, Groovy can take a closure with the same parameters and coerce it to implement the interface.
Using the connection, create an instance of Sql. You could skip this and query with Java, but Groovy's Sql class is so nice.
Use one of the available Sql.call() methods to execute your stored procedure.
In postgress SQL, it is posible to call stored procedure. The catch is returning a data table so that you can map it to a model. This is as shown bellow.
create function activate(confirmationcode text)
returns TABLE(resultid integer, resultmessage character varying)
language plpgsql
as $$
BEGIN
....
END
This can be invoked as follows in GORM db connections
type FuncResult struct {
Resultid int
Resultmessage string
}
...
fResult := FuncResult{}
err := s.db.Raw("SELECT * from activate(?)", token).Scan(&fResult).Error

Open a DataBase Connection within the try parenthesis?

I want to know that is it useful to opan a connection inside parenthesis of try cause at the end there is no need to close that connection it happens automatically..... ?
The value of defining a connection within a using statement is that the variable defined is automatically disposed at the end of the block. It is still good practice to explicitly Close() the connection when you're done using it. Like this in SQL Server:
using(var conn = new SqlConnection(...)) {
...
conn.Close();
}
At the end of the using() block, conn.Dispose() is called automatically even if an exception occurs within the block.

Resources