Skip to content

Instantly share code, notes, and snippets.

@drmcarvalho
Created June 15, 2018 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmcarvalho/21c354d5d38c079af034e375d9a076f6 to your computer and use it in GitHub Desktop.
Save drmcarvalho/21c354d5d38c079af034e375d9a076f6 to your computer and use it in GitHub Desktop.
CRUD exemplo
package cadanime;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author aluno
*/
public class CadAnime
{
public static void main(String[] args) throws SQLException
{
//MostrarAnimes();
//NovoAnime("Tokyo Ghoul:re");
if (AtualizaAnime(2, "Steins;Gate 0")) System.out.println("Atualizado");
else System.out.println("Nao atualizado");
}
static void MostrarAnimes() throws SQLException
{
ResultSet rs = FonteDados.getConn().prepareStatement("SELECT animes.* FROM animes").executeQuery();
if (rs.isBeforeFirst())
while (rs.next())
System.out.print("Anime: " + rs.getString("nome") + "\n\n");
}
static void NovoAnime(String nome) throws SQLException
{
PreparedStatement ps = FonteDados.getConn().prepareStatement("INSERT INTO animes (nome) values (?)");
ps.setString(1, nome);
ps.execute();
}
static boolean DeletaAnime(int id) throws SQLException
{
return FonteDados.getConn().prepareStatement("DELETE FROM animes WHERE id = " + id).executeUpdate() > 0;
}
static boolean AtualizaAnime(int id, String novoNome) throws SQLException
{
PreparedStatement ps = FonteDados.getConn().prepareStatement("UPDATE animes SET nome = ? WHERE id = ?");
ps.setString(1, novoNome);
ps.setInt(2, id);
return ps.executeUpdate() > 0;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cadanime;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author aluno
*/
public class FonteDados
{
public static Connection getConn()
{
try
{
return DriverManager.getConnection("jdbc:mysql://localhost/anime","root", "");
}
catch(SQLException ex)
{
System.err.println("Error: [" + ex.getMessage() + "]");
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment