4:41 am - Wednesday September 26, 2018

Statement PRIMARY KEY Example program in java Jdbc mysql database

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

Primarykey

This tutorial explains how to set a primary key for a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeUpdate to execute the query.  If we wants to change a column constrain to primary key using java use this tutorial

Java code:

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

public class Primarykey {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String Driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/test";
		String uName ="root";
		String pwd = "root";
		Connection conn=null;

		try {
			Class.forName(Driver).newInstance();
			conn = DriverManager.getConnection(url, uName, pwd);
			Statement stmt = conn.createStatement();
			String sql = "Alter table student Add primary key (Roll_No)";
			stmt.executeUpdate(sql);
			System.out.println("primarykey added sucessfully");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

Output:

primarykey added sucessfully

Filed in: Z-A All Java Codes

Comments are closed.