Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
    public static Connection getConnection() throws Exception {
        String driver = "org.gjt.mm.mysql.Driver";
        String url = "jdbc:mysql://localhost/databaseName";
        String username = "root";
        String password = "root";

        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        conn = getConnection();
        stmt = conn.createStatement();
        stmt.executeUpdate("insert into animals_table (name) values('newName')");
        rs = stmt.getGeneratedKeys();
        while (rs.next()) {
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int columnCount = rsMetaData.getColumnCount();

            for (int i = 1; i <= columnCount; i++) {
                String key = rs.getString(i);
                System.out.println("key " + i + " is " + key);
            }
        }
        rs.close();
        stmt.close();
        conn.close();
    }
}