Can't Show database on XAMPP-> mysql to java - java

I am using XAMPP->Mysql to create database and using Netbeans IDE 8.1 fro create java
My Code
//default package
//1st step
import java.sql.*;
public class DemoJDBC {
public static void main(String[] args) {
try{
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
rs.next();
String name = rs.getString("sname");
System.out.println(name);
//6th step
con.close();
}
catch (Exception e){
}
}
}
Why it didn't show output name ? It just show
"BUILD SUCCESSFUL (total time: 1 second)" in netbeans output

You need to loop through the ResultSet to get the tuples or rows. So while looping you retrieve whatever data or field you want to get. try:
public static void main(String[] args) {
try {
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
//6th step
con.close();
} catch (Exception e) {
}
}
NOTE if by default you did not change the password of the root user it is just the empty String (thus "" and not "0"). Other than that you know what you are doing.

Along with the correction of your code to loop through the ResultSet, you also need to correct your connection string as shown below:
Considering that your MySQL is running on the default MySQL port 3306 (which I see that you already are), the connection string needs to be updated.
Also saw that password for the user root is '0', is it really the password?
public static void main(String[] args) {
try {
String query = "SELECT * FROM Student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "0");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
con.close();
} catch (Exception e) {
}
}
Also ensure to have your MySQL Connector/J jar file to be present in your CLASSPATH to not to face any reference issues.
Hope that this helps!

Related

How do I list multiple databases with their tables by using "Show Tables" via Java?

I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA

Using ResultSet to return string value from database but method skips the "Try" clause?

Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");
not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
String result = "";
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
result = rs.getString(colName);
conn.close();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
public static void getValueOf(String sql, String colName, PrintWriter pw)
{
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Based upon your last edit, I would guess that you have more than one records.
So change your code to
if (rs.next()) {
result = rs.getString(colName);
}
And also, your code does not skip that try block

I am trying to connect my java application to hostinger.in(but no output)

I am trying to connect my java application to hostinger.in
I tried this code but no output is displayed.Is this code correct
enter code here
Class.forName(\"com.mysql.jdbc.Driver\");
conn = DriverManager.getConnection(\"jdbc:mysql://mysql.hostinger.in/u869878874_stock\" ,\"u869878874_stock\", \"bhavin\");
stmt = conn.prepareStatement(\"SELECT * FROM logintbl\");
ResultSet rs=null;
rs=stmt.executeQuery();
while (rs.next())
{
usr =usr+rs.getString(\"userid\");
}
jLabel1.setText(usr);
I tried this code but no output is displayed
Is this code correct
Stop using escape sequence in your code and start using string directly.
https://docs.oracle.com/javase/tutorial/java/data/characters.html
Ex.
Class.forName("com.mysql.jdbc.Driver")
Changes to your code.
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet resultSet = null;
String SELECT_SQL = "SELECT * FROM logintbl";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<host>:<port>/<database_name>", "<user id>", "<password>");
pStatement = connection.prepareStatement(SELECT_SQL);
resultSet = pStatement.executeQuery();
for(;resultSet.next();){
System.out.println("User Id " + resultSet.getString("userid"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}

Java retrieving of data in ms access "Column not found" error

i'm trying to program an application that retrieves data from ms access in java. this is my code:
import java.sql.*;
public class testdb {
public static void main(String[] args) {
String path = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\smartphone.accdb";
Statement statement;
ResultSet rs;
Connection con;
String sql = "SELECT dev_name,points FROM list";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(path, "", "");
System.out.println("Connected");
statement = con.createStatement();
statement.executeQuery(sql);
rs = statement.getResultSet();
System.out.println(rs.getString("SELECT dev_name FROM list"));
} catch (Exception ex) {
System.err.println("Got an exception");
System.err.println(ex.getMessage());
}
}
}
it compiles correctly and gives and output of:
Connected
Got an exception
Column not found
please help.
Change
rs.getString("SELECT dev_name FROM list")
to
rs.getString("dev_name")
Also iterare the ResultSet using
while(rs.next())
To iterate the ResultSet you use its next() method. The next() method returns true if the ResultSet has a next record, and moves the ResultSet to point to the next record.If there were no more records, next() returns false.

Java - Getting Data from MySQL database

I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}

Categories

Resources