How to specify database in SQL query with Java - java

I am trying to upload some data to a MySQL database using Java, as I'm working on an Android app. So far, this code compiles and runs, but is uploading nothing to my database. I assume because I'm not accessing the database "streakly" anywhere, but when I've searched around for a way to solve this I haven't found anything.
Snippet of code I'm trying to upload
String addStreakName = chooseName.getText().toString();
String addCategory = prefs.getString("Category", "");
String addToday = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
if(prefs.getInt("todayOrChosen", 1) == 1){
int addStartedZero = 0;
streakList.add(new Streak(addStreakName, addCategory, addToday, addStartedZero));
try {
Connection con = DriverManager.getConnection("127.0.0.1", "[myusername]", "[mypassword]");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO `users`(userId, addStreakName,addCategory,addToday,addStartedZero) VALUE ('"+addStreakName+"', '"+addCategory+"', '"+addToday+"', '"+addStartedZero+"', '"+userID+"')");
} catch (SQLException e) {
e.printStackTrace();
}
}

You are trying to connect to localhost, which in your case is the android device. I am pretty sure there's no MySQL server running on your device, thus the problem you see. You can probably connect to a MySQL server using JDBC driver, but I really wouldn't recommend it. Mobile apps live on users devices, and having direct access to your database server is not such a good idea. If you need a local database, you can use SQLite, Couchbase Lite, Firebase, Realm, etc. If you want to then synchronize with a server, you can either implement an application server and sync via REST for example, or use a solution like Couchbase Lite+Sync Gateway or Google's Firebase
Regards,
Vladimir

Related

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Why is this mySQL database not connecting to Netbeans?

The mysql database will not connect to the netbeans code. I am using a Mac Device and have installed mySQL on my device (it is running fine on localhost:8080). However, the connection through Java is not working. I believe there may be an error in the following line "conn = Driver Manager..." since it is not executing. I am unsure of how to change the password / what the password is.
Restarting Xampp
Screenshot of connection code
Expected result: user input is sent to mySQL database
Actual result (error): seen in this screenshot
This is the general database connectivity code .
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","MysqlUsername","MysqlPassword");
Statement stmt = (Statement) con.createStatement();
String query = "YourMysqlQuery";
stmt.executeUpdate(query);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
// You also have to add 'jdbc driver' in lib folder of your project.
If want us to solve the problem in your code then please provide the actual code you have done , Not the image .

Does Connection Pooling makes Java Swing Application works faster for remote MySQL database

I have Created an Java Swing Application with MySQL as the database, Now i am hosting my MySQL database online and Swing Application will be stored locally, Now in order to experiment i have hosted my database i.e MySQL database on https://www.freemysqlhosting.net/ account as it allows free hosting for certain period, Also Connection is successfull and works but the application works too slow suppose if i have to search any entry from the swing aplication from the oline hosted database it works too slow,it is happening like i have to press any key or button and has to wait for the processing of the transaction. Does connection pooling technique will solve the performance issues, If yes which is best one and if not what can i do to solve this. Please Help
Below is the code which i have written to make database transactions and i am doing this everytime i make a database access
public ArrayList<ChargeSheet> readByAllCompanyInfo(String cityname)
{
ArrayList<ChargeSheet> list = new ArrayList<ChargeSheet>();
con=db.getConnection();
try{
pst = con.prepareStatement("select * from tblcompanyinformation where companyname = ?");
pst.setString(1,cityname);
rs = pst.executeQuery();
while(rs.next()){
ChargeSheet clientInformation=new ChargeSheet();
clientInformation.setRecieptno(rs.getInt(2));
clientInformation.setPresentdate(rs.getString(3));
clientInformation.setCompanyname(rs.getString(4));
clientInformation.setPhone(rs.getString(5));
list.add(clientInformation);
}
}
catch(SQLException ex){
setLastError(ex.getMessage());
}
finally{
db.closeConnection();
}
return list;
}
With that code, it is likely that using a connection pool will improve performance. Especially if you are using SSL-enabled connections.
(Of course, this assumes that you use the same pool for connecting.)
If yes which is best one ....
Recommendations are Off-Topic for StackOverflow, but I'm sure you could find a website that lists and compares some popular alternatives.

querying remote mysql database from java application

I want to be able to able to get a connection to a remote mysql database from a hava application. That is suppose i have a database server in london with user table, and another database server in paris with a product table and i want to be able from anywhere to get connection to these 2 databases and perform operations on them separately from a java application. My hope is to hide details such as ip address where the servers are located. I just want a kind of handle that abstract the lower level details for each of the servers and using this handle get a connection in a java application. Any help will be highly appreciated
I think that this works for me, if it is what you are searching for:
try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database, username, password);
Statement stm = connection.createStatement();
stm.execute("SOME PIECE of SQL CODE HERE");
} catch (SQLException e) {
}
Talking about address and that kind of stuff, if just you will have acess to the application, there's no problem to have your mysql data in the code. But if you will send this code for another people, you might need to create a client/server based application to avoid losing your credentials.

Issue with connection from Google App Engine and Google Cloud SQL on production

When I connect to Google MySQL account locally, it retrieve records from cloud MySQL table. But when I deploy my application on production, records are not coming but 200 OK is coming.
I've already tried
String url = null;
try {
if (SystemProperty.environment.value() ==
SystemProperty.Environment.Value.Production) {
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://your-project-id:your-instance-name/guestbook?user=root";
} else {
// Local MySQL instance to use during development.
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://127.0.0.1:3306/guestbook?user=root";
// Alternatively, connect to a Google Cloud SQL instance using:
// jdbc:mysql://pi-address-of-google-cloud-sql-instance:3306/guestbook?user=root
}
} catch (Exception e) {
e.printStackTrace();
return;
}
I have enable the connector using java 1.7 version
If you have not linked your App Engine's Application ID to the Authorized App Engine Applications' list for Cloud SQL instance, you may need to link those two, because only apps listed there will be allowed to access your Cloud SQL instance; and those must be located in the same region as well.
Also, you should add
<use-google-connector-j>true</use-google-connector-j>
in appengine-web.xml.

Categories