Inserting records into a MySQL table using Java -
i created database 1 table in mysql:
create database iac_enrollment_system; use iac_enrollment_system; create table course( course_code char(7), course_desc varchar(255) not null, course_chair varchar(255), primary key(course_code) );
i tried insert record using java:
// step 1: import required packages import java.sql.*; import java.util.*; public class sqlinsert { // jdbc driver name , database url static final string jdbc_driver = "com.mysql.jdbc.driver"; static final string db_url = "jdbc:mysql://localhost:3306/iac_enrollment_system"; // database credentials static final string user = "root"; static final string pass = "1234"; public static void main(string[] args) { connection conn = null; statement stmt = null; scanner scn = new scanner(system.in); string course_code = null, course_desc = null, course_chair = null; try { // step 2: register jdbc driver class.forname("com.mysql.jdbc.driver"); // step 3: open connection system.out.print("\nconnecting database..."); conn = drivermanager.getconnection(db_url, user, pass); system.out.println(" success!\n"); // step 4: ask user input system.out.print("enter course code: "); course_code = scn.nextline(); system.out.print("enter course description: "); course_desc = scn.nextline(); system.out.print("enter course chair: "); course_chair = scn.nextline(); // step 5: excute query system.out.print("\ninserting records table..."); stmt = conn.createstatement(); string sql = "insert course " + "values (course_code, course_desc, course_chair)"; stmt.executeupdate(sql); system.out.println(" success!\n"); } catch(sqlexception se) { se.printstacktrace(); } catch(exception e) { e.printstacktrace(); } { try { if(stmt != null) conn.close(); } catch(sqlexception se) { } try { if(conn != null) conn.close(); } catch(sqlexception se) { se.printstacktrace(); } } system.out.println("thank patronage!"); } }
the output appears return successfully:
but when select mysql, inserted record blank:
why inserting blank record?
no cannot work(not real data):
string sql = "insert course " + "values (course_code, course_desc, course_chair)"; stmt.executeupdate(sql);
change to:
string sql = "insert course (course_code, course_desc, course_chair)" + "values (?, ?, ?)";
create preparedstatment sql , insert values index:
preparedstatement preparedstatement = conn.preparestatement(sql); preparedstatement.setstring(1, "test"); preparedstatement.setstring(2, "test2"); preparedstatement.setstring(3, "test3"); preparedstatement.executeupdate();
Comments
Post a Comment