Connect to localhost database - java

I got a little question about databases and android. I got this code:
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('Makam','Sai Geetha','India',25);");
and to read:
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
With this code, I make and read the database, and insert some info in it. And print it on the screen, this all works :)
Now the part I can't figure out:
I use myPHPadmin (with xampp),
I made the exact database as I do in the code.
But how do I connect, so my code reads that database.
It is a local database for now (127.0.0.1).
Is it possible to connect a local database? (if so, could you tell me how to)
Do you need PHP, or can you do everything in (Android) Java code?
I am totally new with databases, so sometimes it confusing for me.
Please put me in the good direction.
If you need more information for the question or something else, please let me know.

It is a local database for now (127.0.0.1).
In Android you have to use 10.0.2.2 or System's Static IP.
Write a PHP script (You can also use other but PHP its easy to implement) to manage the database and run this script using HTTP protocol from the android system.
These Tutorials might help you:
Step-by-Step-Method-to-Access-Webservice-from-Andr
Web Services - An XML-RPC Client for Android

As far as I'm aware there is no MySQL library for android. But you can use the HttpPost to send data to a server side script (such as PHP) and then return it in a format you can parse in your Android application.
There's a nice tutorial on how to achieve this here: http://www.helloandroid.com/tutorials/connecting-mysql-database
Here's a link to the HttpPost Documentation: http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html
Hope this helps, this is a good way to get you started communicating with external MySQL databases within an Android application.

Related

What can be causing a foreign key exception when check is on 0?

I'm trying to fix a little plugin that I'm making for MineCraft servers. The plugin uses code that tries to automatically adjusts to the server needs, first converting the tables on old tables, creating the new ones and after using some objects that contains human decisions to parse or update specific information to the new tables, parsing all the data that is not duplicated already to the new tables, then removing the old ones.
The code is kinda messy, I didn't had lot of time this days, but I was trying to get a free week to remake all the code of the plugin. The problem is that everything was working fine, but one day I decided to update the plugin on a server that I use for testing, that is using MySQL. The problem in this server is that I was using the same code all the time and I didn't had problems, but after some time without using it, now it's not working.
This is the part of the code that is failing:
protected boolean tables() {
boolean update = false, result = update;
if (!this.sql.execute(
"CREATE TABLE IF NOT EXISTS information(param VARCHAR(16),value VARCHAR(16),CONSTRAINT PK_information PRIMARY KEY (param));",
new Data[0]))
return false;
List<String> tlist = new ArrayList<>();
try {
this.sql.execute("SET FOREIGN_KEY_CHECKS=0;", new Data[0]);
ResultSet set = this.sql.query("SELECT value FROM information WHERE `param`='version';", new Data[0]);
String version = "";
if (set.next())
version = set.getString(1);
if (!version.equals(MMOHorsesMain.getPlugin().getDescription().getVersion())) {
update = true;
ResultSet tables = this.sql.query("SHOW TABLES;", new Data[0]);
while (tables.next()) {
String name = tables.getString(1);
if (!name.equals("information")) {
if (!this.sql.execute("CREATE TABLE " + name + "_old LIKE " + name + ";", new Data[0]))
throw new Exception();
if (!this.sql.execute("INSERT INTO " + name + "_old SELECT * FROM " + name + ";", new Data[0]))
throw new Exception();
tlist.add(name);
}
}
String remove = "";
for (String table : tlist)
remove = String.valueOf(remove) + (remove.isEmpty() ? "" : ",") + table;
this.sql.reconnect();
this.sql.execute("DROP TABLE IF EXISTS " + remove + ";", new Data[0]);
The database stores an extra data that it's the version of the plugin. I use it to check if the database is from another version and, if that's the case, regenerate the database. It's working fine on SQLite, but the only problem comes here on MySQL.
The first part gets the actual version and checks. The plugin starts disabling the foreign keys. This is not the best part but as I said, I didn't actually had time to remake all this code, also this code comes from a compiled version cause due some GitHub issues I lost part of the last updates. If it requires the update, it starts transforming every table on _old tables. Everything works fine here, data is parsed to the _old tables and is managed correctly, but the problem is when it has to removes the original tables.
DROP TABLE IF EXISTS cosmetics,horses,inventories,items,trust,upgrades;
This is the SQL statement that is used to remove the original ones, but, I don't know if it works like that, but if that's the case, the _old tables got the foreign keys that the original tables too and when I try to remove them, it doesn't allow, even if the FOREIGN_KEY_CHECKS is on 0. I also set a debug before to check if the checking was disabled and it was. To simulate the best environment where people is used to work, I'm using a prebuilder minecraft hosting from a friend, using MariaDB 10.4.12.
I'm asking him if he updated it since the last time I was preparing this server, but I'm still waiting for his answer. Anyway, even if it's a newer or older MariaDB version, what I'm trying is to make it the most elastic possible so it can be adapted to different versions without problems. Everything seems to work fine, but as I can't delete the original databases, I can't replace them with the new format.
I wish this is just an error that happens with certain DB configurations, but I'd like to get an answer of someone with knowledge to make sure I didn't upload a broken version.
Thanks you nicomp, the answered was keeping the same session. My reconnect method is not really flexible, as I came from some strange experiences of high latency and like 1 sec sessions, cause after nothing it was getting disconnected easily, and was detecting incorrectly the connection so it was reconnecting and removing the configuration of the session.

Java persistancemanager fetch return less entities

In java fetching entities with query some time return less entities in some rare case. I am using javapersistance manager. Is it ideal to use it or need to switch to low level datastore fetch to solve it?
String query = "CUID == '" + cuidKey + "' && staffKey == '" + staffKey +"'&& StartTimeLong >= "+ startDate + " && StartTimeLong < " + endDate + " && status == 'confirmed'";
List<ResultJDO> tempResultList = jdoUtils.fetchEntitiesByQueryWithRangeOrder(ResultJDO.class, query, null, null, "StartTimeLong desc");
The result returned 4 entities in rare case, but most time return all 5 entities.
jdoUtils is a PersistanceManager object.
Should I need to switch to low level datastore fetch for exact results.
I have tried researching about the library you mentioned and for similar issues and found nothing that far. It's hard to know why this is happening or how to fix it with as little information.
On the other hand, the recommended way of programmatically interact with Google Cloud Platform products is through Google's client libraries since they are already tested and assured to work in almost all cases. Furthermore, their usage allows to open Github issue's if you find any problem so that the developers could address them. For the rare cases that you need some functionality not already covered you can open a feature request or directly call the API's.
In addition to Google's libraries there are two other options for Java that are under active development. One is Objectify and the other is Catatumbo.
I would suggest switching to Java Datastore libraries. You could find examples on how to interact with Datastore in link1 and link2. Also you could find community shared code samples in this programcreek page.

Why will following sql-statement not work with JDBC?

I am programming a basic database management system in java. When the user submits his username and password, the program will search in a database of the submitted data is correct:
result = stat.executeUpdate("SELECT username,password FROM DB" + "WHERE (username = '"+loginusr.getText()+"',password = '"+loginpwd.getText()+"')");
Apparently there is an error near the = sign. Can someone help figuring this out?
Thanks in advance
A couple of issues there.
First, you need a space before the WHERE:
result = stat.executeUpdate("SELECT username,password FROM DB" + "WHERE (username = '"+loginusr.getText()+"',password = '"+loginpwd.getText()+"')");
// Here ---------------------------------------------------------^
But the more fundamental issue is that you've left that code wide open to SQL injection attacks and failures. Use PreparedStatement, don't concatenate strings to put your parameters in. Here's a nice illustration of why:
From: http://xkcd.com/327/
And finally: It's not best practice to store passwords in a database. Instead, typically you store a cryptographic hash of the password, not the password itself (SHA-256 is one hashing technique, for instance). Then when the user is authenticating, you hash what they gave you as their password and compare it with the hash you have stored. That way, the password cannot be retrieved from the database.
Apart from the general advice not to use string concatenation for SQL queries, but parameters instead, there is a mistake in the source: …DB" + "WHERE… has no space.
Your text expands to:
SELECT username,password FROM DBWHERE (username = ...
You need to add a space in to your string and use AND rather than ,, e.g.:
result = stat.executeUpdate("SELECT username,password FROM DB " +
"WHERE (username = '"+loginusr.getText()+"' AND password = '"+loginpwd.getText()+"')");
However, bear in mind that if this is an example of real code, there are at least two major security issues that should also be addressed.

Call Stored Procedures in a java client application

So, my problem is: I've developed some REST services with Jersey, in Glassfish 3.1.2, that were generated from my MySQL database. Then I've implemented Basic-Authentication. That's all working fine.
Now, I'm developing a client application to consume those services. I've used Apache HttpClient to the authentication, and I've already tried the GET method, and the PUT method. I can obtain the values from my DataBase, and update others, with the aid of a JSON object.
But how can I use the Stored Procedures that I have in my database, to do a PUT/POST and update my DataBase??
Thanks
You will need to use JDBC, something like this
cs = this.con.prepareCall("{call SHOW_SUPPLIERS()}");
ResultSet rs = cs.executeQuery();
while (rs.next())
{
String supplier = rs.getString("SUP_NAME");
String coffee = rs.getString("COF_NAME");
System.out.println(supplier + ": " + coffee);
}
As an example, see following documentation (where I got the above code from)
http://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html

SQLite DB is locked exception, how do I unlock it if I haven't ever toyed with it?

java.sql.SQLException: database is locked
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NestedDB.prepare(NestedDB.java:115)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89)
When I make a query I get this exception. I read up on it on SA and Google, and the most common conclusion is that someone started making another query which never finished. The problem I'm having is that I've never made a query on this DB on this machine before. I downloaded the db file from where I hosted it (I created it earlier) and haven't done anything with it, so I don't know why it would be locked. When I do a query using a program called SQLite Database Browser, it works just fine. Thanks for the help, I'll provide more info if need be, just let me know.
adapter = new DbAdapter();
ResultSet info;
ResultSet attributes;
for (int i = 1; i < 668; i++) {
if (i%50 == 0) {
System.out.print('.');
}
info = adapter.makeQuery("SELECT * FROM vehicles WHERE id = '" + i + "'");
attributes = adapter.makeQuery("SELECT * FROM vehicle_moves WHERE vehicle_id = '" + i + "'");
if(info.next()) {
base = new (info, attributes);
}
vehicleArray[i] = base;
}
System.out.println("Done.");
info.close();
attributes.close();
adapter.close();
Above is the code where this is occurring. I did some homework throughout my code and sure enough the problem is in this code, other DB queries work just fine. Anything jump out at you guys?
SQLite itself can most certainly handle doing a query while the results of another query are being processed. It'd be terribly useless if that couldn't be done! What's more likely to cause problems is if you've got two connections to the database open at once. I don't know that DbAdapter class at all – not what package it is in, or what module provides it – but if it is assuming that it can open many connections (or if it isn't maintaining proper connection hygiene) then that most certainly would be a cause of the sort of problems you're seeing. Look there first.

Categories

Resources