See also: MySQL XAMPP Connection for Java jdbc Program
Let's see the following table:
Now follow these steps:
See also:
Reference
Let's see the following table:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create table user ( | |
id int unsigned auto_increment not null, | |
first_name varchar(25) not null, | |
last_name varchar(25) not null, | |
age int not null, | |
primary key (id) | |
); |
Now follow these steps:
- Create a Java Connection to our MySQL database.
- Define SQL SELECT statement.
- Then execute the SELECT query, getting a Java ResultSet from that query
- Now iterate over the ResultSet, getting the database fields (columns) from each row of data that is returned
- Close our Java MySQL database connection.
- Finally catch any SQL exceptions using try-catch clause.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mysqlconn; | |
import java.sql.*; | |
import java.util.*; | |
public class Mysqlconn { | |
public static void main(String[] args)throws SQLException { | |
try { | |
String url="jdbc:mysql://localhost:3306/newdatabase"; | |
Properties prop=new Properties(); | |
prop.setProperty("user","root"); | |
prop.setProperty("password",""); | |
Driver d = new com.mysql.jdbc.Driver(); | |
Connection con = d.connect(url,prop); | |
if(con == null) { | |
System.out.println("connection failed"); | |
return; | |
} | |
String query = "SELECT *FROM user"; | |
Statement state = con.createStatement(); | |
ResultSet result = null; | |
state.executeQuery(query); | |
while(result.next()){ | |
// fetching result from database | |
String fname = result.getString("first_name"); | |
String lname = result.getString("last_name"); | |
int age = result.getInt("age"); | |
System.out.println("First Name: " + fname + ", Last Name: " + lname + ", Age: " + age); | |
} | |
state.close(); | |
} catch (Exception e) | |
{ | |
System.err.println("Got an exception!"); | |
System.err.println(e.getMessage()); | |
} | |
} | |
} |
See also:
Reference
No comments:
Post a Comment