class and methods to Manage MySQL database

MySQL How to insert data to MySQL table

Our main class ( my_main.java ) uses the constructor and class of my_update to insert record to MySQL student table.

my_main.java

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

class my_update{
	String str1;
	String str2;
	int str3;
	String str4;
 
void my_db_update() {
	//System.out.println("Data: " + str1 + str2+ str3 + str4);
	try{  
	Class.forName("com.mysql.jdbc.Driver");  
	Connection con=DriverManager.getConnection(  
	"jdbc:mysql://localhost:3306/my_tutorial","root","test");  
	Statement st=con.createStatement();  
			
		// Adding record 
	String query1="INSERT INTO `my_tutorial`.`student`"
	 + " (`name`, `class`, `mark`, `sex`)"
	 + "VALUES('" +str1+"','"+str2+"','"+str3+"','"+str4+"')";
	st.executeUpdate(query1);
	ResultSet rs = null;
	rs = st.getGeneratedKeys();
	rs.next();
	int new_id=rs.getInt(1);
	System.out.println("Data inserted, id  is : "+ new_id);
		// Display the record just now inserted. 
	rs=st.executeQuery("SELECT * FROM STUDENT WHERE id="+new_id); 
	rs.next();  
	System.out.println(rs.getInt(1)+" "
		+rs.getString("name")+" "+rs.getString("mark"));
			
	con.close();  
	}catch(Exception e){ System.out.println(e);} 
	//////////////////////////////
}
}

public class my_main {

	public static void main(String[] args) {
		
		my_update  myObj = new my_update();
		myObj.str1="My Name";
		myObj.str2="Four";
		myObj.str3= 43;
		myObj.str4="Male";
		
		myObj.my_db_update();
	}
}
MySQL MySQL student table dump


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer