<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Últimas mensagens do tópico "Exemplo de PreparedStatement"]]></title>
		<link>http://www.guj.com.br/posts/list/4.java</link>
		<description><![CDATA[Últimas mensagens enviadas no tópico "Exemplo de PreparedStatement"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>Exemplo de PreparedStatement</title>
				<description><![CDATA[ Olá Pessoal,<br /> <br /> To com um grande problema li uma vez aqui que era melhor trabalhar com PreparedStatement, e comecei a estudar só que tem hora que funciona e tem hora que não funciona, será que alguém poderia me dar um exemplo usando preparedStatement ou mesmo me indicar algum tutorial, eu já li no Deitel e lá não encontrei nada, a baixo eu motro um exemplo de um método que eu crieie<br /> <br /> private void insereDadosGeral(Medidas medidas, Amostra amostra, String sql){<br />         try{<br />             PreparedStatement prst = con.prepareStatement(sql);<br />             st = prst;<br />             prst.setDate(1, new java.sql.Date(amostra.getIdent().getDataEntrevista().getTime()));<br />             prst.setDate(2, new java.sql.Date(amostra.getIdent().getDataNascimento().getTime()));<br />             prst.setString(3, amostra.getIdent().getNaturalidade());<br />             prst.setString(4, amostra.getIdent().getCursoSetor());<br /> ...<br /> <br />  }catch(Exception e){<br />           System.out.println("Erro: " + e);  <br />         }<br /> <br /> Desde já agradeço<br /> <br /> Marcelo Logan]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/214215/exemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/214215/exemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 25 Aug 2006 13:41:18]]> GMT</pubDate>
				<author><![CDATA[ loganwlogan]]></author>
			</item>
			<item>
				<title>Re:Exemplo de PreparedStatement</title>
				<description><![CDATA[ [code]<br /> try{	<br /> 	// cria um preparedStatement<br /> 	PreparedStatement stmt = con.prepareStatement("insert into contatos (nome,email,endereco) values (?,?,?)");<br /> <br /> 	// preenche os valores<br /> 	stmt.setString(1, ?xxx?);<br /> 	stmt.setString(2, ?contato@xxx.com.br?);<br /> 	stmt.setString(3, ?R. xxxx 12?);<br /> <br /> 	// executa<br /> 	stmt.execute();<br /> 	stmt.close();<br /> <br /> 	System.out.println("Gravado!");<br /> <br /> 	con.close();<br /> <br /> } catch (SQLException e) {<br /> 	 e.printStackTrace();<br /> }<br /> <br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/214233/reexemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/214233/reexemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 25 Aug 2006 14:07:54]]> GMT</pubDate>
				<author><![CDATA[ zepunk]]></author>
			</item>
			<item>
				<title>Re:Exemplo de PreparedStatement</title>
				<description><![CDATA[ Um bom exemplo de query:<br /> [code]<br /> try {<br />             Vector vCadastros = new Vector();<br />             conn = ConnectionManager.getConexao();<br />             stmt = conn.createStatement();<br />             rs = stmt.executeQuery(SELECT_ALL_QUERY);<br /> <br />             while (rs.next()) {<br /> <br />             	int id = rs.getInt("id");<br />                 String nome = rs.getString("nome");<br />                 String dataNasc = rs.getString("dataNasc");<br />                 String sexo = rs.getString("sexo");<br />                 double rg = rs.getFloat("rg");<br /> <br />  Cadastro p = new Cadastro(id, nome, dataNasc, sexo, rg);<br />                 vCadastros.add(p);<br />             }<br />             CatalogoCadastros catalogo = new CatalogoCadastros(vCadastros);<br />             return catalogo;<br /> catch{<br /> <br /> (...)<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/214404/reexemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/214404/reexemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 25 Aug 2006 18:18:27]]> GMT</pubDate>
				<author><![CDATA[ bebad]]></author>
			</item>
			<item>
				<title>Re:Exemplo de PreparedStatement</title>
				<description><![CDATA[ Quando vc precisar de exemplos java em outras ocasiões, um bom site é o <br /> <a class="snap_shots" href="http://www.javaalmanac.com/" target="_blank" rel="nofollow">http://www.javaalmanac.com/</a><br /> <br /> []´s<br /> Rodrigo]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/214417/reexemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/214417/reexemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 25 Aug 2006 18:58:43]]> GMT</pubDate>
				<author><![CDATA[ rodrigo_gomes]]></author>
			</item>
			<item>
				<title>Exemplo de PreparedStatement</title>
				<description><![CDATA[ Boas, realmente este tópico ajuda-me um pouco. Mas não vai ao encontro das minhas espectativas. <br /> O que eu queria era ter de evitar a parte de preparar o stmt. <br /> [code]<br /> // preenche os valores  <br />     stmt.setString(1, ?xxx?);  <br />     stmt.setString(2, ?contato@xxx.com.br?);  <br />     stmt.setString(3, ?R. xxxx 12?);  <br /> [/code]<br /> <br /> <br /> o código que tenho é este e serve de base a todas as minhas outras classes.<br /> [code]<br /> package ConnectionDataBase;<br /> <br /> /**<br />  * @author Tiago Agostinho<br />  * @version V 2.0<br />  * */<br /> import java.sql.*;<br /> <br /> public class sqlQuerys {<br /> <br />     private Statement stmt = null;<br />     private ResultSet rs = null;<br />     private int res;<br />     private ConectBD con;<br /> <br />     /**<br />      * @param DB - Nome da Base de Dados<br />      * @param user - Username de acesso a Base de Dados<br />      * @param pass - Password de acesso a Base de Dados<br />      * */<br />     public sqlQuerys(String DB, String user, String pass){<br />         con = new ConectBD(DB, user, pass);<br />     }<br /> <br />     /**<br />      * @param sql - Recebe a String sql para fazer o insert na Base de Dados<br />      * @return Retorna o numero de linhas inseridas<br />      * @throws<br />      * */<br />     public boolean insert(String sql, String[] arg1) throws SQLException {<br />     	<br />     	PreparedStatement stmt = con.getConection().prepareStatement(sql, arg1);<br />     	<br />     	boolean res = stmt.execute();<br />     	stmt.close();<br />     	<br />     	return res;<br />     	//Obter um statement<br />         //Statement stmt = con.getConection().createStatement();<br /> <br />         //executar o comando de Update seguido de um select<br />         //res = stmt.executeUpdate(sql);<br />     }<br /> <br />     /**<br />      * @param sql - Recebe a String sql para fazer o delete na Base de Dados<br />      * @return Retorna o numero de linhas deletadas<br />      * @throws<br />      * */<br />     public int delete(String sql) throws SQLException {<br /> <br />         //Obter um statement<br />         Statement stmt = con.getConection().createStatement();<br /> <br />         //executar o comando de Update seguido de um select<br />         res = stmt.executeUpdate(sql);<br /> <br />         stmt.close();<br /> <br />         return res; // false<br /> <br />     }<br /> <br />     /**<br />      * @param sql - Recebe a String sql para fazer o select a Base de Dados<br />      * @return Retorna o ResultSet com os dados pretendidos<br />      * @throws<br />      * @see Also ResultSet<br />      * */<br />     public ResultSet select(String sql) throws SQLException {<br /> <br />         stmt = con.getConection().createStatement();<br /> <br />         rs = stmt.executeQuery(sql);<br /> <br />         return rs;<br />     }<br /> <br />     /**<br />      * @param sql - Recebe a String sql para fazer o update na Base de Dados<br />      * @return Retorna o numero de linhas que foram alteradas<br />      * @throws<br />      * */<br />     public int update(String sql) throws SQLException {<br />         //Obter um statement<br />         Statement stmt = con.getConection().createStatement();<br /> <br />         //executar o comando de Update seguido de um select<br />         int result = stmt.executeUpdate(sql);<br /> <br />         stmt.close();<br /> <br />         return result;<br />     }<br /> <br />     /**<br />      * return Retorna a conecï¿½ï¿½o ï¿½ base de dados<br />      * @see Also Connection<br />      * */<br />     public Connection getConection() {<br />         return con.getConection();<br />     }<br /> <br />     /**<br />      * @throws<br />      * @since Liberta o Statement, permitindo optimizaï¿½ï¿½o de espaï¿½o<br />      * @see Statement<br />      * */<br />     public void freeStatement() throws SQLException {<br />         stmt.close();<br />     }<br /> <br />     /**<br />      * @throws<br />      * @since Liberta o ResultSet, permitindo optimizaï¿½ï¿½o de espaï¿½o<br />      * @see ResultSet<br />      * */<br />     public void freeResultSet() throws SQLException {<br />         rs.close();<br />     }<br /> <br />     /**<br />      * @throws<br />      * @param url - Recebe o URL de ligaï¿½ï¿½o ï¿½ base de dados<br />      * @since Abre a connecï¿½ï¿½o ï¿½ base de dados, &lt;br&gt;<br />      * 		permitindo que a aplicaï¿½ï¿½o comunique com a interface<br />      * */<br />     public void open() {<br />         con.open();<br />     }<br /> <br />     /**<br />      * @throws<br />      * @since Fecha a connecï¿½ï¿½o a base de dados,permitindo optimizaï¿½ï¿½o de espaï¿½o<br />      * */<br />     public void close() {<br />         con.close();<br />     }<br /> <br />      public void testConect() {<br /> <br />         open();<br />         close();<br /> <br />     }<br /> }<br /> <br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/1198899/exemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/1198899/exemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Sat, 12 Feb 2011 09:10:38]]> GMT</pubDate>
				<author><![CDATA[ tmagostinho]]></author>
			</item>
			<item>
				<title>Re:Exemplo de PreparedStatement</title>
				<description><![CDATA[ Use o Spring.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/1198909/reexemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/1198909/reexemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Sat, 12 Feb 2011 09:40:02]]> GMT</pubDate>
				<author><![CDATA[ ViniGodoy]]></author>
			</item>
			<item>
				<title>Re:Exemplo de PreparedStatement</title>
				<description><![CDATA[ Leia o capitulo 2 da apostila FJ-21 da caelum que fala sobre JDBC  a apostila é free<br /> Todos os exemplos usam o preparedStatement  <br /> www.caelum.com.br a ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/1252191/reexemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/1252191/reexemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 20 May 2011 12:55:53]]> GMT</pubDate>
				<author><![CDATA[ vbdalmaz]]></author>
			</item>
			<item>
				<title>Exemplo de PreparedStatement</title>
				<description><![CDATA[ [quote=tmagostinho]Boas, realmente este tópico ajuda-me um pouco. Mas não vai ao encontro das minhas espectativas. <br /> O que eu queria era ter de evitar a parte de preparar o stmt. <br /> [/quote]<br /> <br /> Sua classe pode ser um Data Access Object. Porém, sua expectativa será meio frustrada, pois sempre-se deve preparar a statement se você está trabalhando direto com JDBC.<br /> <br /> Você pode utilizar biblitecas como o Hibernate para uma solução mais "completa" de base de dados, ou algo como o Apache Commons-DBUtils para ajudar na parte da execução das queries. <br /> 5<br /> Mas, LEMBRE-SE, sempre que trabalhar direto com base de dados, você tem de dar close em TUDO que abriu. Algo como, nos finally:<br /> <br /> [code]try {<br />  ...<br /> } catch (SQLException e) {<br />  //tratar exception<br /> } finally {<br /> <br /> 			if (rs != null) {<br /> 				try {<br /> 					rs.close();<br /> 				} catch (SQLException sqle) {<br /> 					logger.debug("SQLE on close", sqle);<br /> 				}<br /> 			}<br /> 			if (ps != null) {<br /> 				try {<br /> 					ps.close();<br /> 				} catch (SQLException sqle) {<br /> 					logger.debug("SQLE on close", sqle);<br /> 				}<br /> 			}<br /> 			if (c != null) {<br /> 				try {<br /> 					c.close();<br /> 				} catch (SQLException sqle) {<br /> 					logger.debug("SQLE on close", sqle);<br /> 				}<br /> 			}<br /> 		}<br /> }[/code]<br /> <br /> <br /> Isso libera os recursos tanto no seu programa, quanto no servidor.<br /> <br /> No seu código, seja educado: feche tudo o que abriu. Se não fechar, explicite bem o motivo de não fechar e o fato no seu java doc!!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/1252231/exemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/1252231/exemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Fri, 20 May 2011 13:33:19]]> GMT</pubDate>
				<author><![CDATA[ leo.andven]]></author>
			</item>
			<item>
				<title>Exemplo de PreparedStatement</title>
				<description><![CDATA[ Quero pedir desculpa pela minha ausência aqui no forum, mas por motivos diversos não foi possível estar cá!<br /> Eu vou então ler a apostilha recomendada.<br /> Espero então depois conseguir optimizar a pesquisa pois está a começar a ficar muito lento. :S<br /> <br /> Mais uma vez obrigado pela vossa atenção!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/40126/1265281/exemplo-de-preparedstatement
</guid>
				<link>http://www.guj.com.br/prepost/40126/1265281/exemplo-de-preparedstatement
</link>
				<pubDate><![CDATA[Sun, 12 Jun 2011 14:22:03]]> GMT</pubDate>
				<author><![CDATA[ tmagostinho]]></author>
			</item>
	</channel>
</rss>
