Hi everyone.
So I get the code going now the question is:
How to make a menu in Java code?
For example:
1.create table
2.insert into table
3.select fro table
4.delete table...
Which will you choose: ex.1
and creates table
I mean like switch case in C++

import java.sql.*;

public class dbAccess
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database = 
              "jdbc:odbc:Driver:myDB";
            Connection conn = DriverManager.getConnection(database, "", "");
            Statement s = conn.createStatement();
            
            // the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable); 
            
            // second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }
            
            // this should be third case:Fetch table
            String selTable = "SELECT * FROM " + tableName;
            s.execute(selTable);
            ResultSet rs = s.getResultSet();
            while((rs!=null) && (rs.next()))
            {
                System.out.println(rs.getString(1) + " : " + rs.getString(2));
            }
            
            // this should be the 4: drop the table
            String dropTable = "DROP TABLE " + tableName;
            s.execute(dropTable);
            
            // close and cleanup
            s.close();
            conn.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Help anyone???

Dani AI

Generated

A compact, practical pattern for a single-class Swing menu: create a JFrame (or a small dialog) with a row of JButtons (Create / Insert / Select / Drop). Register ActionListeners (or Actions) on each button; schedule GUI creation on the Event Dispatch Thread and run any database work off the EDT (SwingWorker or a background thread) so the UI never freezes. (docs.oracle.com)

Keep the UI wiring simple inside one class by giving each button an ActionListener that calls a small private helper method (e.g., doCreateTable(...), doInsert(...)). For long or I/O-bound tasks call a SwingWorker from the listener so the UI stays responsive and updates can be posted back safely. The Java Swing tutorials cover the ActionListener and button basics. (docs.oracle.com)

Use a proper JDBC driver (not the old sun.jdbc.odbc bridge) and parameterized SQL for user-supplied values. The JDBC-ODBC bridge was deprecated/removed and Oracle recommends vendor drivers; for MySQL use Connector/J. Use PreparedStatement for INSERT/UPDATE/SELECT values and try-with-resources (or finally blocks) so connections, statements and result sets are always closed. These practices also reduce SQL injection risk. (docs.oracle.com)

Table names are special: they cannot be bound as parameters. Either whitelist allowed names, verify a supplied name exists via DatabaseMetaData, or safely quote the identifier per your DB (MySQL uses backticks). Example pattern: build the SQL only after validating/quoting the identifier, then use a PreparedStatement for the values:

// validate tableName against a whitelist or lookup; then:
String sql = "INSERT INTO " + quoteIdentifier(tableName) + " (id,name) VALUES (?, ?)";
try (Connection c = DriverManager.getConnection(url,user,pw);
     PreparedStatement ps = c.prepareStatement(sql)) {
    ps.setInt(1, id);
    ps.setString(2, name);
    ps.executeUpdate();
}

For validation and metadata checks see DatabaseMetaData.getTables; for guidance on identifier quoting and injection risks see the JDBC/OWASP materials. (stackoverflow.com)

Notes and quick checks: put the JDBC driver JAR on the classpath, test SQL directly in the database console first, log SQLExceptions with full stack traces, and avoid long DB work on the EDT. This keeps a small single-class Swing app tidy and safe while matching the menu/button approach discussed earlier by and for input and selection.

Recommended Answers

All 7 Replies

Hi everyone.
So I get the code going now the question is:
How to make a menu in Java code?
For example:
1.create table
2.insert into table
3.select fro table
4.delete table...
Which will you choose: ex.1
and creates table
I mean like switch case in C++

import java.sql.*;

public class dbAccess
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database = 
              "jdbc:odbc:Driver:myDB";
            Connection conn = DriverManager.getConnection(database, "", "");
            Statement s = conn.createStatement();
            
            // the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable); 
            
            // second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }
            
            // this should be third case:Fetch table
            String selTable = "SELECT * FROM " + tableName;
            s.execute(selTable);
            ResultSet rs = s.getResultSet();
            while((rs!=null) && (rs.next()))
            {
                System.out.println(rs.getString(1) + " : " + rs.getString(2));
            }
            
            // this should be the 4: drop the table
            String dropTable = "DROP TABLE " + tableName;
            s.execute(dropTable);
            
            // close and cleanup
            s.close();
            conn.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Help anyone???

If you want a command line based menu, its similar to C++
Use print staements as you do in C++ and take the input
by Using either Scanner or DataInputStream and depending upon the input use switch case as you do in C++ (switch case only take integer input).
If you want GUI based (swing) menu u can use JMenuBar, JMenu and JMenuItem class and their listeners accordinly

Well I want to try with JMenu or something like that. I just want to make (for example) buttons for every case. Can someone give me some code example? And can I make it in the same class? I just want to make it simple and I don't want to make another class. THANKS!!!!!

If you want to use GUI compents like JMenu you will have to write java swing code for that.

Refer the JMenu tutorial for a clear example.

But if you are looking at a quick way for the user to make a selection and invoke it, try the following:

Object[] choices= {"create", "insert", "delete"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Make a selection:",
                    "Your Menu Choices",
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    choices,
                    "create");
if ((s != null) && (s.length() > 0)) {
    if (s.equals("create")){
         // write your create code
    } else if (s.equals("delete")){
         // write your delete code
    }else if (s.equals("insert")) {
        // write your insert code
    }
}

Thanks a lot. I'm relatively new in Java and I've never worked with JMenu, but I'll try. If it doesn't work I'll go with the selection part.
THANKS A LOT!!!!!

I have one more question:
How to change this code so I could name the table:
For example create a table: "Table1", because here the table is already named. Also how to add your own data into the table, not random numbers like in this code.

// the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable);

and this:

// second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }

Help with a little example code please?
THANK YOU!!!!

I have one more question:
How to change this code so I could name the table:
For example create a table: "Table1", because here the table is already named.

// the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable);
String tableName = "Table1";

Also how to add your own data into the table, not random numbers like in this code.
and this:

// second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }

Help with a little example code please?
THANK YOU!!!!

for(int i=0; i<25; i++)
            {
              int id = 123; // Here you can assign whatever ID you want
              String strid =  String.valueOf(id); 
              String name = "Ram"; //Here you can assign whatever name you want
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     strid + ", '" + name + "')";
              s.execute(addRow);
            }

THANK YOU!!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.