Import java.sql.*;
Import java.util.ArrayList;
Import java.util.List;
Import Com.mysql.jdbc.ResultSetMetaData;
public class Mysqlhelper {
Test connection function
public static void Main (String []args)
{
Derbyhelper de=new derbyhelper ();
String sql= "SELECT * from users";
List<object[]> list=de.querylist (SQL, NULL);
for (int i=0;i<list.size (); i++)
{Object []obj=list.get (i);
System.out.println (obj[1].tostring () + "" +obj[2].tostring ());
}
}
MySQL Connection property settings
String driver= "Com.mysql.jdbc.Driver";
String url= "Jdbc:mysql://192.168.1.114:3306/test";
String user= "root";
String passwd= "1234";
Connection classes and Interfaces
Connection CT;
PreparedStatement PS;
ResultSet rs;
Public Mysqlhelper ()
{
try {
Class.forName (driver);
Ct=drivermanager.getconnection (URL,USER,PASSWD);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public int Update (String sql,string []paras)
{
int count=0;
try {
Ps=ct.preparestatement (SQL);
Injection parameters
This.setparameters (paras);
Gets the number of updated data rows.
Count=ps.executeupdate ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
This.close ();
}
return count;
}
/**
* @param sql
* @param paras No injection parameters can be null or empty string.
* @return Returns a resultset result set.
*/
Public ResultSet query (String sql,string[] paras)
{
try {
Ps=ct.preparestatement (SQL);
This.setparameters (paras);
Rs=ps.executequery ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
Not off.
}
Return RS;
}
/**
* @param sql
* @param paras No injection parameters can be null or empty string.
* @return Returns a list containing an array of objects.
*/
Public List querylist (String sql,string []paras)
{
List<object[]> list=new arraylist<object[]> ();
try {
Ps=ct.preparestatement (SQL);
This.setparameters (paras);
Rs=ps.executequery ();
ResultSetMetaData rsmd= (ResultSetMetaData) rs.getmetadata ();
int Count=rsmd.getcolumncount ();
Place the query results in an array of objects.
while (Rs.next ())
{int rows= rs.getrow ();
Object Obj[]=new Object[count];
for (int j=0;j<count;j++)
{obj[j]=rs.getstring (j+1);
}
List.add (obj);
}
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{this.close ();}
return list;}
public void Close ()
{
try {
if (rs!=null) rs.close ();
if (ps!=null) ps.close ();
if (ct!=null) ct.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
private void Setparameters (String[] paras) throws SQLException {
if (Paras!=null &&!paras.equals (""))
{for (int i=0;i<paras.length;i++)
{
Ps.setstring (i+1, paras[i]);
}
}
}}
Java uses MySQL database code