Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.mysql.jdbc.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class SqlTest {
- public static void main(String[] args) throws ClassNotFoundException, SQLException {
- Class.forName("com.mysql.jdbc.Driver");
- // connecting to the database
- java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://db4free.net:3306/database_name?useSSL=false", "username","password");
- // how to read from the database
- PreparedStatement state = con.prepareStatement("select * from student");
- // Resultset takes the data as a iterable array
- ResultSet result = state.executeQuery();
- System.out.println("\n reading from the database \n");
- // iterable resultset is printed
- // result.getString(1) implies first column and each loop represents a row
- while(result.next()){
- System.out.println(result.getString(1)+" "+result.getString(2)+" " + result.getString(3));
- }
- // how to write to the database
- Statement stmt = con.createStatement();
- // ususal SQL commands as Strings
- stmt.executeUpdate("INSERT INTO student " +
- "VALUES (2354,'Nimal','Perera')");
- result = state.executeQuery();
- System.out.println("\nAfter writing to the database \n");
- while(result.next()){
- System.out.println(result.getString(1)+" "+result.getString(2)+" " + result.getString(3));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement