mercredi 22 juin 2016

how to delete data from mysql database with jndi in my jsp file

i wanna try to delete data from my table i succeed when i use normal connect but i trued to use jndi but i failed

it's strange that i can do "select * from users" query with the same method,but delete failed instead.

this is my jsp file about delete

    String jndiName = "java:/comp/env/" + "jdbc/write_mysql";       
    Context initContext = (Context) new InitialContext();
    DataSource ds = (DataSource)initContext.lookup(jndiName);

    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("delete from users where user_id ='1';");
    conn.close();

i tried to use variables in my user_id,but failed so i specified user_id ='1';

i can success in my Mysql command line with the same query

and this is my context.xml file

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/read_mysql" 
          auth="Container" 
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/sampledb"
          username="root" password="********" defaultAutoCommit="false"
          maxActive="3" maxIdle="0" maxWait="10000" />

<Resource name="jdbc/write_mysql" 
          auth="Container"      
          type="javax.sql.DataSource"
          factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/sampledb"
          username="root" password="********" defaultAutoCommit="false"
          maxActive="3" maxIdle="0" maxWait="10000" />
</Context>

but when i do it with direct connect and i success(but i want to try jndi,it looks better to trace code)

String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "********";

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(dbURL, username, password);
Statement stmt = conn.createStatement();
String query = "delete from users where user_id ='"+index+"';";
stmt.executeUpdate(query);

Aucun commentaire:

Enregistrer un commentaire