First up, I apologise if this is a duplicate in any way, but I have been trying many different things from this site for several hours now with no luck. And for the record, I am running OS X 10.11.5.
I have made this simple application using JDBC to connect to a database I created that is stored on my localhost (I am using phpMyAdmin, if that is any help):
#Override
public void actionPerformed(ActionEvent e) {
// The ID to search for
int search = Integer.parseInt(textField.getText());
// Setting up the connection to the database.
String url = "jdbc:mysql://my_ip_address:3306/javaDatabase";
String user = "root"; // root user
String password = ""; // no password
Connection con = null;
PreparedStatement searchID; // I used a prepared statement so I could include user input
ResultSet result = null; // results after SQL execution
try {
con = DriverManager.getConnection(url, user, password); // connect to MySQL
// Creating the prepared statement
searchID = con.prepareStatement("SELECT * FROM Names WHERE ID = ?");
// Setting the parameter to the user input
searchID.setInt(1, search);
result = searchID.executeQuery(); // execute the SQL query
while (result.next()) { // loop until the end of the results
String ID = result.getString("ID");
String FirstName = result.getString("FirstName");
String LastName = result.getString("LastName");
textArea1.setText("ID: " + ID + "\n" +
"First Name: " + FirstName + "\n" +
"Last Name: " + LastName + "\n");
}
} catch(SQLException e1) {
System.out.println("Exception caught " + e1.getMessage());
} finally {
try {
if (result != null) {
result.close();
}
if (con != null) {
con.close();
}
} catch(SQLException e2) {
System.out.println("SQLException caught " + e2.getMessage());
}
}
}
public static void main(String[] args) {
JavaWithSQL newJava = new JavaWithSQL();
}
Now, I am packaging this application up as an executable .JAR file, and want to be able to run it on someone else's computer and have it access the database and return the records.
I have tried instructions from here and here, without any luck. I looked at opening port 3306 on my Mac, but my firewall is off, but that doesn't seem to be the problem. I have also attempted to use GRANT privileges on the database in question using:
GRANT ALL PRIVILEGES ON javaDatabase.* TO '%'#'%' IDENTIFIED BY '';
to no avail. However, it does work on other computers when I explicitly write the computers IP address, like this:
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'other_computer_ip' IDENTIFIED BY '';
But I need to be able to run it on my lecturer's computer, and in theory, other people's computers, without having to know everyone's IP addresses.
How can I do this? Am I missing something?
EDIT:
Okay, I have run the command
GRANT SELECT ON javaDatabase.* TO 'remoteUser'#'%' IDENTIFIED BY '';
FLUSH PRIVILEGES;
And now it works perfectly on any computer connected to the same network, but I need it to work even if I am connected to a different network.
I really need a pointer on this one.
You are using TO '%'#'%' IDENTIFIED BY '';
I'm not sure if that works. It should address the root user in your case.
GRANT ALL PRIVILEGES ON javaDatabase.* TO 'root'#'%' IDENTIFIED BY '';
Related
I'm working in Yii2 with the Adldap extension found here: https://github.com/Adldap2/Adldap2
I'm running into an issue when I try to authenticate users on my ldap server. I can successfully make a connection and and retrieve user data, but when trying to authenticate if a user's username and password are correct or not, it always returns true, even if the creds are wrong. Below is my code snippet (with the config array not showing of course):
$ad->addProvider($config);
try {
// If a successful connection is made to your server, the provider will be returned.
$provider = $ad->connect();
//User below does return the correct information from the ldap server
$user = $provider->search()->users()->find('quillin');
try{
$provider->auth()->attempt("wrongUsername","wrongPassword");
die("WIN");
}catch( Exception $e ){
die("Exception " . $e);
}
}catch (\Adldap\Auth\BindException $e) {
die( "There was an issue binding / connecting to the server. <br />" . $e);
}
No matter what I put in for the username and password fields, it always returns true and hits the die("WIN"); line. In my composer.json file, i'm using "adldap2/adldap2": "v7.0.*"
I have also tried to bind the user using the following:
try{
$provider->auth()->attempt("wrongUsername","wrongPassword", $bindAsUser = true);
die("WIN");
}catch( Exception $e ){
die("lose :(");
die("Exception " . $e);
}
And that also always returns true;
I figured this out and will explain here in anyone else has the same issue.
1) $provider->auth()->attempt() should be wrapped in an IF, and not a try/catch.
2) The first parameter, $username, is actually looking for the userprincipalname, the docs had made it sound like it was looking instead for a username.
After that, I was able to authenticate the user successfully.
I am using Auth0 for a login service but I have a need to add a user to a database in MySQL every time an account is registered through Auth0.
They give this following script template but I am a newbie and need help debugging and understanding it. My specific questions are detailed as comments:
function create(user, callback) {
var connection = mysql({
host: 'localhost', //what should this be?
user: 'KNOWN/Understood',
password: 'KNOWN/Understood',
database: 'KNOWN/Understood'
});
connection.connect();
var query = "INSERT INTO users SET ?"; //what does this do?
bcrypt.hash(user.password, 10, function (err, hash) { //what does this do?
if (err) { return callback(err); }
var insert = {
password: hash,
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
});
}
Is there anything else I need to change for this script or understand or call in for it to work?
I often get the error missing username for Database connection with requires_username enabled and I'm unsure what this means.
I'm assuming you already went through this tutorial on custom databases so let's address your specific questions.
host: 'localhost' // What should this be?
This and the other properties of this object define the way to connect to your custom MySQL database. The database needs to be reached from within Auth0 servers so this needs to be a host name accessible from the Internet.
"INSERT INTO users SET ?"; // What does this do?
This defines an SQL insert command that uses ? as a placeholder for later substitution.
If you see where this query is later used, you will noticed it's invoked with an additional insert object parameter that will cause the above query to be expanded into something like:
INSERT INTO users SET email = 'user#example.com', password = 'asdf34ASws'
bcrypt.hash(user.password, 10, function (err, hash) // What does this do?
This hashes the user provided password so that it's not stored in plain text in the database.
If you chose to require a username in addition to email you need to address this in your custom scripts as I believe the default templates assume that only email will be used.
This means that when creating the user in your database you also need to store the username and in the script to verify a user you also need to return the username.
We are writing a specialized PHP e-mail client and would like to give administrators of this client the ability to create user accounts on hMailServer.
I tried out imap_createmailbox(...) but it just creates a directory in the user's folder structure but does not "create a mailbox for a new user" as we want.
Is there some kind of interface that hMailServer has so that I can enable our PHP e-mail client to create hMailServer accounts via code?
Yes there two interfaces to create accounts in hmailserver.
One, via database, you can choose account and password hash type (0,1,2,3) and signature and other classic informations. I don't recommend this method for synchronisation reason, hmail-server take a caching time to consider the database update.
Two, which i recommend is to use API COM, its offers all possible methods in all cummon languages.
You have to enable D-COM in your windows server.
The API guide
hmailserver version: hMailServer 5.6.4 - Build 2283
complete solution of create new email account by hmailserver in c#
if you have configured hmailserver successfully, so then you can use the following steps to create new account by hmailserver in c#
hmailserver connection
private Domain HMailServerConnection() {
var objGlobal = new ApplicationClass();
objGlobal.Authenticate(ConfigurationManager.AppSettings["HMailUsername"], ConfigurationManager.AppSettings["HMailPassword"]);
return objGlobal.Domains.get_ItemByName(ConfigurationManager.AppSettings["hMailDomain"]);
}
function to create new email account
public string AddNewAccount(string email,string password)
{
try
{
Domain domain = HMailServerConnection();
Accounts accounts = domain.Accounts;
Account mailbox = accounts.Add();
mailbox.Address = email;
mailbox.Password = password;
mailbox.Save();
return "success";
}
catch(Exception ex)
{
return "error";
}
}
App settings in App.config or web.config
<appSettings>
<add key="hMailDomain" value="domainname"/>
<add key="HMailUsername" value="Username"/>
<add key="HMailPassword" value="password"/>
</appSettings>
see the link
its working i tested it.
<?php
header('Content-Type: text/html; charset=utf-8');
$obBaseApp = new COM("hMailServer.Application", NULL, CP_UTF8);
$obBaseApp->Connect();
$hmail_config['rooturl'] = "http://localhost/";
$obAccount = $obBaseApp->Authenticate("Administrator", "hMailserver Administrator
password");
if (!isset($obAccount)) {
echo "<b>Not authenticated or Administrator's password wrong</b>";
} else {
try {
echo "<b>Logon COM [OK], now we can add accounts</b>";
$obDomain = $obBaseApp->Domains->ItemByDBID(1);
$obAccount = $obDomain->Accounts->ItemByDBID(1); // account id
$domainname = $obDomain->Name;
$obAccounts = $obDomain->Accounts();
$obAccount = $obDomain->Accounts->Add();
$newalias = "powerranger";
$firstname = "Arnold";
$lastname = "Schwarzenegger";
$my_domainname ="#mydomain.com";
$obAccount->PersonFirstName = $firstname;
$obAccount->PersonLastName = $lastname;
$obAccount->MaxSize = 102; // 102 MB set inbox space
$obAccount->Address = $newalias .$my_domainname;
$obAccount->Password = "secret"; // provide this in Thunderbird/Outlook ect.
$obAccount->Active = true; // set account to active
$obAccount->Save(); // save, finish.
/* If we reaching this point, everything works as expected */
echo "<br/><h3> Account was successfully created, now you can login with".
"an POP3 or IMAP-Client </h3>";
}
/* OK, if something went wrong, give us the exact error details */
catch(Exception $e) {
echo "<h4>COM-ERROR: <br />".$e->getMessage()."</h4><br />";
}
}
Normally we check if replication on slaves is working via the console command
SHOW SLAVE STATUS \G;
I would like to incorporate this functionality into a servlet reporting application.
However, hibernate does not seem to allow this :
createSQLQuery("SHOW SLAVE STATUS");
...executing query...
java.lang.UnsupportedOperationException: not yet implemented for SQL queries
I'm sure it's possible to achieve this using native JDBC, however maybe there is a better way?
Environment: Linux 2.6.18, Tomcat 6/7, Hibernate 3.4, Java 1.6, MySQL 5
Note: I'm not interested in solutions where we insert timestamps on master.
When you use createSQLQuery to run a native SQL query, you have to tell Hibernate how to convert the results into Java objects. The easiest way in your case is to add
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
to the query before executing it. (If the query returned already-mapped Entities, you could just use addEntity().)
I haven't tried hard enough to make this work with Hibernate, but if that fails, you can still use a good old-fashioned JDBC connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
static final String DB_ADDRESS = "localhost";
static final String DB_NAME = "mysql";
static final String DB_USER = "root";
public static void main (String[] args) {
// get password
String password = "";
if (args!=null && args.length>0) {
password = args[0];
}
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
System.out.println("Driver issue: " + ex.getMessage());
System.out.println("Driver issue: " + ex.getClass().toString());
}
// connect to database
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://"+DB_ADDRESS+"/"+DB_NAME+"?autoReconnect=true",DB_USER,password);
// Do something with the Connection
System.out.println("Connection: " + conn);
Statement stmt = conn.createStatement();
ResultSet RS = stmt.executeQuery("SHOW TABLES");
while (RS.next()) {
System.out.println("table: '" + RS.getString(1) + "'");
}
// disconnect from database
conn.close();
stmt.close();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}
This would return:
Connection: com.mysql.jdbc.JDBC4Connection#528acf6e
table: 'columns_priv'
table: 'db'
table: 'event'
table: 'func'
table: 'general_log'
table: 'help_category'
table: 'help_keyword'
table: 'help_relation'
table: 'help_topic'
table: 'host'
table: 'ndb_binlog_index'
table: 'plugin'
table: 'proc'
table: 'procs_priv'
table: 'proxies_priv'
table: 'servers'
table: 'slow_log'
table: 'tables_priv'
table: 'time_zone'
table: 'time_zone_leap_second'
table: 'time_zone_name'
table: 'time_zone_transition'
table: 'time_zone_transition_type'
table: 'user'
Needless to say, the key thing is to ensure your user has sufficient privileges.
This works for me..
SQLQuery query =session.createSQLQuery("show slave status");
ArrayList<Object[]> results = (ArrayList<Object[]>)query.list();
//there is only one row returned
Object [] result = results.get(0);
//Seconds Behind Master should always be the last value in the row.
String secondsBehindMaster = ""+result[result.length-1];
Ensure DB user has REPLICATION CLIENT permission to make this query.
GRANT REPLICATION CLIENT ON *.* TO 'db_user'#'db_server' IDENTIFIED BY 'db_password';
As the message of the UnsupportedOperationException exception suggests, getReturnTypes() is not implemented by the SQLQuery object returned by createSQLQuery().
By the way, the phrasing of your question is misleading, you do not receive the exception on calling createSQLQuery(), but a few lines later.
When you issue native SQL, you will retrieve rows as a list of generic Object[] (unless you explicitely provide Hibernate with a mapping). Typically, the types will be known at compile-time.
See here for more information.
I have a local and a remote connection with my mysql database. The local connection works just fine. But the remote connection, while it makes a connection, it does not return anything. I usually get the following:
Fatal error: Call to a member function result() on a non-object
I use for the remote connection the following configuration:
$db['mydb']['hostname'] = "ip_address_of_database";
$db['mydb']['username'] = "username";
$db['mydb']['password'] = "password";
$db['mydb']['database'] = "database";
$db['mydb']['dbdriver'] = "mysql";
$db['mydb']['dbprefix'] = "";
$db['mydb']['pconnect'] = FALSE;
$db['mydb']['db_debug'] = FALSE;
$db['mydb']['cache_on'] = FALSE;
$db['mydb']['cachedir'] = "";
$db['mydb']['char_set'] = "utf8";
$db['mydb']['dbcollat'] = "utf8_general_ci";
In my function that accesses the database I check if there is a connection with the remote server and then I try to retrieve data.
$mydb = $this->load->database('mydb', TRUE);
if (!isset($mydb->conn_id) && !is_resource($mydb->conn_id)) {
$error = 'database is not connected';
return $error;
}else{
$query = $mydb->query("SELECT * FROM database LIMIT 1;");
return $query->result();
}
This works fine in the localhost database but not in the remote database. I allways get the error
Fatal error: Call to a member function result() on a non-object
Can you please help? What am I doing wrong? I stuck on this.
Finally, I found the solution after contacting my web hosting provider. The issue had to do with the Remote database access and their servers. The IP address exception and the domain name that I had added didn’t do the job. I had to add an internal domain name that my host was using in order the Remote database access to be allowed. I spent 2-3 hours chatting with them in order to find a solution.
Anyway now is solved. I am posting that FYI.