Created
October 14, 2013 02:53
-
-
Save matiasfha/6969968 to your computer and use it in GitHub Desktop.
Java y MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javamysql; | |
import java.sql.*; | |
public class Main { | |
//variables | |
private static Connection conexion; | |
private static String bd="javamysql"; | |
private static String user="test"; | |
private static String password="123"; | |
private static String host="localhost"; | |
private static String server="jdbc:mysql://"+host+"/"+bd; | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
//conectar | |
try { | |
Class.forName("com.mysql.jdbc.Driver"); | |
conexion = DriverManager.getConnection(server,user,password); | |
System.out.println("Conexión a base de datos "+server+" ... OK"); | |
} catch (ClassNotFoundException ex) { | |
System.out.println("Error cargando el Driver MySQL JDBC ... FAIL"); | |
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); | |
} catch (SQLException ex) { | |
System.out.println("Imposible realizar conexion con "+server+" ... FAIL"); | |
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
//realizar consulta | |
try { | |
// Preparamos la consulta | |
Statement s = conexion.createStatement(); | |
ResultSet rs = s.executeQuery ("select * from persona"); | |
// Recorremos el resultado, mientras haya registros para leer, y escribimos el resultado en pantalla. | |
while (rs.next()) | |
{ | |
System.out.println( | |
"ID: " +rs.getInt (1) + | |
"tNombre: " + rs.getString (2)+ | |
"tSexo: " + rs.getString("sexo") | |
); | |
} | |
} catch (SQLException ex) { | |
System.out.println("Imposible realizar consulta ... FAIL"); | |
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
//desconectar | |
try { | |
conexion.close(); | |
System.out.println("Cerrar conexion con "+server+" ... OK"); | |
} catch (SQLException ex) { | |
System.out.println("Imposible cerrar conexion ... FAIL"); | |
//Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment