Android Studio Sql Server Connection - java

I'm making an app in android studio with connection to a SQL database server, I have a problem in connecting to the database.
Code:
import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import net.sourceforge.jtds.jdbc.*;
Log.i("Android", " MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
//String connString = "jdbc:jtds:sqlserver://localhost:1433/quehojaes;encrypt=false;user=Pc-PC;password=;instance=SQLEXPRESS;";
// String connString = "Data Source=localhost:1433;Initial Catalog=quehojaes;Integrated Security=True";
String connString ="jdbc:jtds:sqlserver://localhost:1433/quehojaes;";
String username = "Pc-PC";
String password = "";
conn = DriverManager.getConnection(connString);
Log.w("Connection", "open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from planta where id=1");
//Print the data to the console
while (reset.next()) {
dato = reset.getString(3);
Log.w("Data:", reset.getString(3));
Log.w("Data",reset.getString(2));
}
conn.close();
} catch (Exception e) {
Log.w("Error connection", "" + e.getMessage());
}
return dato;
}
.................................
I got an error at line (conn = DriverManager.getConnection (connString)), so I guess it is wrong user I'm trying to get into the database, I enter Windows user authentication with a local database and I have no password for that user called Pc.
There are lines discussed by failed login attempts I've tried.
Thanks for the help!

localhost means your current machine. That would be the phone. Since SQLServer isn't running on your phone, its the wrong string. Use your PCs IP address, and make sure you can access that port through any ISP or personal firewalls.
As an aside- this is a HORRIBLE way to do things. You have to put your password the the SQL server in your app. Its trivial to decompile it and own your data. Instead you should put up a web service inbetween the two, so only machines you own on your local network need to have the db password.

Related

DB Derby Database stops functioning once connected to DBeaver

Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html

How to connect a Java application to db4free.net using JDBC?

I'm doing a college project where we have to build a fully functioning Java application, complete with a basic user login system using JDBC.
The basic user login system works fine when used on XAMPP's MariaDB MySQL branch via localhost.
Obviously, the system wouldn't work outside of this particular network, so I looked around for ways to allow me to host a MySQL database online at all times so regardless of where I go, this basic user login system works and can be shown to anyone who's interested.
I then found db4free.net, and so far everything looks in order - PHPMyAdmin works, and I managed to successfully export and import the database with the usernames and passwords from the localhost version to db4free's version.
But I'm having trouble on how to actually point my application to connect to db4free's systems so the login system works as intended.
Here's the "connection module" Java class that handles the connection:
package com.fixer.dal;
import java.sql.*;
public class Connection_Module {
public static Connection connector(){
java.sql.Connection cnx = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://db4free.net:3306/db_fixer";
String user = "myuser";
String password = "mypassword";
try {
Class.forName(driver);
cnx = DriverManager.getConnection(url, user, password);
return cnx;
} catch (Exception e) {
return null;
}
}
}
And here's the function that checks with the database to see if the username and password match with the recorded data (and if it does, it closes the login screen and opens the "main" screen):
Connection cnx = null;
PreparedStatement pst = null;
ResultSet rs = null;
public void login(){
String sql = "select * from usertable where username=? and password=?";
try {
pst = cnx.prepareStatement(sql);
pst.setString(1, Screen_Login_Username_Field.getText());
pst.setString(2, Screen_Login_Password_Field.getText());
rs = pst.executeQuery();
if(rs.next()){
Screen_Main Main = new Screen_Main();
Main.setVisible(true);
this.dispose();
cnx.close();
}else{
JOptionPane.showMessageDialog(null, "Invalid user or password.");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And that's mostly my problem. db4free.net gave me a host ("db4free.net") and a port ("3306"), but I don't know exactly where do they go. I've tried some methods to get it to work based off other questions here but none successfully connected me to my database on their systems.
What am I doing wrong?
I just created a database (for the first time) in db4free.com and I used:
MySQL 8.x JDBC driver (I used the JDBC driver 8.0.11).
The URL is:
jdbc:mysql://db4free.net:3306/database-name
In MySQL 8.x, however, it's better to add the following parameters to avoid dealing with tons of warnings:
jdbc:mysql://db4free.net:3306/database-name?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
It worked like a charm at once. Did you confirm the email they sent? Is your account active? Are you using the JDBC driver 8.x?

Connection between Java and MySql

I am trying to make a connection between Java and my data base. I am using Eclipse and xampp. I am almost convinced that I have good config of Eclipse and xampp, but maybe I missed something. I searched a lot on the Internet, but I have not found the solution.
My error are:
SQLException: Could not create a connection to database server. Attempted to reconnect 3 times. Giving up.
SQLState: 08001
VendorError: 0
Xampp -
Xampp config
Eclipse -
I have jar files in the workspace folder.
Eclipse config
phpmyadmin -
I do not need a password to log into localhost/phpmyadmin and I have only one record in DB.
Code
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC2 {
static String daneZBazy;
static String polaczenieURL = "jdbc:mysql://localhost:3306/heroes.db?
autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "root";
public static void main(String[] args) {
// Question to DB
String query = "Select * FROM heroestab";
Connection conn = null;
try {
// Connection parameters
conn = DriverManager.getConnection(polaczenieURL, login, password);
// MySQL Driver
Class.forName("com.mysql.jdbc.Driver");
// Start question to DB
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
wyswietlDaneZBazy(rs);
}
conn.close();
}
//throws exception
catch (ClassNotFoundException wyjatek) {
System.out.println("Driver error");
}
catch (SQLException wyjatek) {
wyjatek.printStackTrace();
System.out.println("Login problem. Check, username, password, DB name, IP adress");
System.out.println("SQLException: " + wyjatek.getMessage());
System.out.println("SQLState: " + wyjatek.getSQLState());
System.out.println("VendorError: " + wyjatek.getErrorCode());
}
}
static void wyswietlDaneZBazy(ResultSet rs) {
try {
daneZBazy = rs.getString(1);
System.out.println("\n" + daneZBazy + " ");
daneZBazy = rs.getString(2);
System.out.println(daneZBazy + " ");
daneZBazy = rs.getString(3);
System.out.println(daneZBazy);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Please verify that both the username and password are correct.
I need the full stack trace from:
wyjatek.printStackTrace();
If the username (root) and password are incorrect, you will see the below line in your stacktrace:
Access denied for user 'root'#'localhost' (using password: YES)
If I remember correctly, with default xampp config, you can try this:
user: root
password: [blank]
static String login = "root";
static String password = "";
I can see my databases useing cmd:
C:\xampp\mysql\bin > mysql -u root -p
Enter
show databases ; and then I can see all databases which I have on localhost. When i
chose heroes and I can select * from heroes ;
Picture:
Database cmd

MySQL issue using Netbeans

OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.

phpMyAdmin and Java Connection

I am trying to connect my java program to a database that i have created using phpmyadmin using a university server. so the database is on the university server. how do i get the connection to the db from the java program? i have tried this code, but it gives me an error message?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Connector {
Connection con;
PreparedStatement stmt;
ResultSet rs;
Connector()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("https://NAMEHIDDEN.soi.city.ac.uk:5454/~kdhy546","root","");
stmt=con.prepareStatement("select * from staff where username=? and password=?");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I am not too sure even, whether this is the correct url to the database? how do i determine the exact link to the database in phpmyadmin?
phpMyAdmin in not a DBMS, it's an UI. If it's a MySQL database, you must use the MySQL JDBC
I have never used phpMyAdmin, but according to this tutorial you should get the connection string if you navigate to the MySQL Account Maintenance Section.
Another thing I am noticing is that you are missing your password in your connection, so without a password your application will not be able to connect.
Lastly, whenever you post a question on SO regarding some code which yields an error, please make sure you include the error, it helps us help you :).
Use the following code.
This is the java part:
import java.net.*;
public class mc
{
public static void main(String args[])
{
try
{
String username="ankur",password="ankur",fname="Shubhendu",ip="12345",lname="Goswami";
String up= "username=" + username + "&password=" + password + "&fname=" + fname + "&lname=" + lname + "&ip="+ ip;
URL url=new URL("http://127.0.0.1:80/alias1/index.php?"+up);
URLConnection urlc=url.openConnection();
urlc.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String str;
while((str=br.readLine())!=null)
{
System.out.print(str);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
PHP part: Anything you will echo from PHP will be stored in String str in Java code:
<?php
mysql_connect("localhost","root","")or die("unable to connect to server");
mysql_select_db("db_name") or die("Unable to connect to database");
$username=$_GET['username'];
$password=md5($_GET['password']);
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$ip=$_GET['ip'];
if(isset($username) && isset($password) && isset($fname) && isset($lname) && isset($ip))
{
$query="INSERT INTO tablename values('$username','$password','$fname','$lname','$ip')";
$fire=mysql_query($query);
}
?>
Hope it works.
Your URL to the database you created with phpMyAdmin is wrong. It should look something similar to:
jdbc:oracle:thin:#//myhost:1521/orc
I recommend you to have a web search for some good Java tutorials on this subject. :)

Categories