Question

Write a JAVA program to create a table named FoodItem that contains the following columns :...

Write a JAVA program to create a table named FoodItem that contains the following columns : ID (number), Name(varchar), calories(number).

Now create an insert statement to insert a record into this database table.

Finally using a select statement print the record that you entered into the database.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

from the given questions list I am going to explain about each question in step wise manner.

let start the process:

step 1: first we have to connect database. step 2: now we have to create table using executeUpdate method(), and the java code will be like this:

 import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class CreateTableFoodItem { private static final String CREATE_TABLE_SQL="CREATE TABLE FoodItem (" + "ID INT," + " NAME VARCHAR," + "CALORIES NUMBER"); public static void main(String[] args) { String Url = "here address of database in your system"; String username = "username of your database"; string password = "password of your database"; connection conn = null; Statement stmt = null; try { conn = Driveranager.getConnection(url, username, password); stmt = conn.createStatement(); stmt.executeUpdate(CREATE_TABLE_SQL); System.out.println("table created"); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } }

now the table has been created in the database and the table will be look like this:

Field Type
ID INT
Name VARCHAR
Calories NUMBER

step 3: now let us see how to use INSERT statement to insert a record in the table.

NOTE: for every connection of database with java use this code


string url = "url of your database";
string username = "username of your database";
string password = "password of your database";

try (Connection conn = DriverManager.getConnection(url , username, password);
Statement stmt = conn.createStatement();

now the java code for INSERT statement is:

 String query = "insert into users(ID, Name, Calories)" + " values(?,?,?)"; PreparedStatement preparedStmt = conn.prepareStatement(query); preparedStmt.setString (1, 001); preparedStmt.setString (2, "IceCream"); preparedStmt.setString (3, 400); preparedStmt.execute(); conn.close(); } catch (Exception e) { System.err.println("Got an exception!"); System.err.println(e.getMessage()); }

step 4: now let us see how to use select statement to get the record that i entered into the database

the java code to select the record is:

 public static void main(string[] args) { string url = "url of your database"; string username = "username of your database"; string password = "password of your database"; string sql = "select * from Fooditem"; try (Connection conn = DriverManager.getConnection(url , username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql):) { int row = 0; while (rs.next()) { System.out.println("row" + row); System.out.println("ID" + rs.getstring(1)); System.out.println("row" + rs.getstring(2)); System.out.println("row" + rs.getstring(3)); System.out.println(); } } catch (SQLException e) { e.printStackTrace(); } } } 

now the output for this code will be like this

ID Name Calories
001 Icecream 400

Hope you got the answer and please rate it.

Add a comment
Know the answer?
Add Answer to:
Write a JAVA program to create a table named FoodItem that contains the following columns :...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a Java program that contains a method named ReadAndFindMax. The argument to this method is...

    Write a Java program that contains a method named ReadAndFindMax. The argument to this method is the filename (of String type). The method opens the file specified in the method argument filename and then reads integers from it. This file can contain any number of integers. Next, the method finds the maximum of these integers and returns it. The main method must first ask the user to enter the filename; then call ReadAndFindMax method with the entered filename as an...

  • For this problem, assume salesperson data are stored in a database table named staff. Also assume the columns in the table are named name, carsSold, and totalSales Write a Python function named ge...

    For this problem, assume salesperson data are stored in a database table named staff. Also assume the columns in the table are named name, carsSold, and totalSales Write a Python function named getSalesSortedByNames. Your function will have 2 parameters. The first parameter is a database cursor and the second parameter is a float. Your function should start by retrieving those rows in the staff table whose totalsales field is equal to the second parameter. (The next paragraph shows the Python...

  • CREATE TABLE DEPT ( DEPTNO INTEGER NOT NULL, DNAME VARCHAR(14), LOC VARCHAR(13), PRIMARY KEY (DEPTNO)); INSERT...

    CREATE TABLE DEPT ( DEPTNO INTEGER NOT NULL, DNAME VARCHAR(14), LOC VARCHAR(13), PRIMARY KEY (DEPTNO)); INSERT INTO DEPT VALUES (10,'SPORTS','NEW YORK'); INSERT INTO DEPT VALUES (20,'HOME','DALLAS'); INSERT INTO DEPT VALUES (30,'OUTDOOR','CHICAGO'); INSERT INTO DEPT VALUES (40,'CLOTHING','BOSTON'); CREATE TABLE EMP ( EMPNO INTEGER NOT NULL, ENAME VARCHAR(10), JOB VARCHAR(9), MGR INTEGER, SAL FLOAT, COMM FLOAT, DEPTNO INTEGER NOT NULL, FOREIGN KEY (DEPTNO) REFERENCES DEPT (DEPTNO), FOREIGN KEY (MGR) REFERENCES EMP(EMPNO), PRIMARY KEY (EMPNO)); INSERT INTO EMP VALUES (7839,'KING','PRESIDENT',NULL, 5000,NULL,10); INSERT INTO...

  • Last name is Vhora 3. Write a java class named FinalyourLastName, which contains three methods: main,...

    Last name is Vhora 3. Write a java class named FinalyourLastName, which contains three methods: main, arrayMystery, and countTotalOdd. You need to create main method. Inside the main method...you need to create an integer array named myld that consists of each of the digits in your student ID, call arrayMystery method and print out myld, then call count TotaOdd method and print out the total number of odd digits in your ID. (8 points) The arrayMystery method is given as...

  • 1.Write a PHP function that generates a random email. 2.Write a PHP function that generates a...

    1.Write a PHP function that generates a random email. 2.Write a PHP function that generates a random password given the length as a parameter. 3. Run a query that will generate a database named lab4 b. 4.Run a query that will create a table named users, the table will only have three columns, email TEXT and password TEXT, ID INTEGER NOT NULL AUTO_INCREMENT. ID will be the primary key that will be generated for us automatically based on the record...

  • The purpose of this Java application is to create a simple user interface on top of...

    The purpose of this Java application is to create a simple user interface on top of a relational database. The database you should use is the Java DB database. Setup of the Java DB database is covered in section 24.5. The user interface will allow a user to insert, delete, and update names from a table in the database. The database table will look like this: ID FIRST_NAME LAST_NAME 1452962065165       Rita                           Red                           1452962067770       Oscar                          Orange                        1452962070010       Yet                            The ID value...

  • A matrix named mach contains 3 columns of data concerning the energy output of several machines....

    A matrix named mach contains 3 columns of data concerning the energy output of several machines. The first column contains an ID code for a specific machine, the second column contains the total amount of energy produced by that machine in calories, and the third column contains the amount of time required by that machine to produce the energy listed in column 2 in hours. Write a MATLAB program that will: a) Request the user for the matrix mach. b)...

  • Database Management 6. [5] Create the following table: CREATE TABLE customer ( cust_name VARCHAR(30) NOT NULL,...

    Database Management 6. [5] Create the following table: CREATE TABLE customer ( cust_name VARCHAR(30) NOT NULL, address VARCHAR(60), UNIQUE (cust name, address)); A. Run the following inserts and explain why both work and how will you prevent it INSERT INTO customer VALUES ('Alex Doe', NULL); INSERT INTO customer VALUES ('Alex Doe', NULL); 7. [5] Modify the following table definition to ensure that all employees have a minimum wage of $10 CREATE TABLE employee ( empId INT PRIMARY KEY, empName VARCHAR(40)...

  • 1. Write a script that creates a user-defined database role named OrderEntry in the MyGuitarShop database....

    1. Write a script that creates a user-defined database role named OrderEntry in the MyGuitarShop database. Give INSERT and UPDATE permission to the new role for the Orders and OrderItems table. Give SELECT permission for all user tables. 2. Write a script that (1) creates a login ID named “RobertHalliday” with the password “HelloBob”; (2) sets the default database for the login to the MyGuitarShop database; (3) creates a user named “RobertHalliday” for the login; and (4) assigns the user...

  • 2. Write a program named lab3 2.app that contains a class named Student to store student...

    2. Write a program named lab3 2.app that contains a class named Student to store student information Information that will be relevant to store is first name, last name, id number, GPA, and major (1) Define a member function named set0, which allows you to set all member variables. This function has an empty parameter list, and its return type is void. So, within the function you'll prompt for information. Note: For entering major, if you need a space, use...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT