Ejemplos JDBC

package com.trifulcas.country;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class AddCountry {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Introduzca el nombre del país");
		String pais = scanner.nextLine();
		try {
			 Class.forName("com.mysql.cj.jdbc.Driver");
			 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "");
	         Statement st=con.createStatement();
	         int res=st.executeUpdate("insert into country (country) values('"+pais+"')");
	         System.out.println("Se han insertado "+res+" registros");
	         st.close();
	         con.close();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

}

package com.trifulcas.country;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class DeleteCountry {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Introduzca el id del país a eliminar");
		String pais = scanner.nextLine();
		try {
			 Class.forName("com.mysql.cj.jdbc.Driver");
			 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "");
	         Statement st=con.createStatement();
	         int res=st.executeUpdate("delete from country where country_id="+pais);
	         System.out.println("Se han eliminado "+res+" registros");
	         st.close();
	         con.close();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}

}


package com.trifulcas.country;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class UpdateCountry {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Introduzca el id del país a modificar");
		String id = scanner.nextLine();
		System.out.println("Introduzca el nuevo nombre");
		String pais = scanner.nextLine();
		try {
			 Class.forName("com.mysql.cj.jdbc.Driver");
			 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "root", "");
	         Statement st=con.createStatement();
	         int res=st.executeUpdate("update country set country='"+pais+"' where country_id="+id);
	         System.out.println("Se han modificado "+res+" registros");
	         st.close();
	         con.close();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}

	}

}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos