Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.Statement;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Org.testng.annotations.Test;
public class Getmysqldata {
Public Map<object, Object> getData (String sqlconn, string account, string password, string sql, string[] renamestr)
Throws Exception {
1. Load the MySQL JDBC driver
Class.forName ("Com.mysql.jdbc.Driver");
2. Get a connection to the database
Connection conn = drivermanager.getconnection ("jdbc:mysql://" +sqlconn, account, password);
3. Through database connection operation database, realize adding and removing to change the search
Statement stmt = Conn.createstatement ();
4. Execute SQL and return the result set, get to the Row object
ResultSet rs = stmt.executequery (SQL);
Used to store the obtained column names and values
Map<object, object> invoicemain = new Hashmap<object, object> ();
Determine if a record is queried
if (!rs.next ()) {
throw new Alertexception ("No query to corresponding record");
}
Before placing the pointer over the first row
Rs.beforefirst ();
Get total number of columns
int cloumcount = Rs.getmetadata (). getColumnCount ();
Constructs a string array with a total number of columns, holding the column names
string[] Cloumname = new String[cloumcount];
for (int i = 0; i < Cloumcount; i++) {
Cloumname[i] = Rs.getmetadata (). getColumnName (i + 1);//The column name pointer in the result set starts at 1, not 0
System.out.println (Rs.getmetadata (). getColumnName (i + 1));
}
5. Remove the required fields from the result set
while (Rs.next ()) {
for (int i = 0; i < cloumname.length; i++) {
Object key = Renamestr[i];
Object value = rs.getstring (i + 1);
if (key.equals ("Invoice type")) {
if (Value.equals ("1")) {
Value = "GPO";
} else if (Value.equals ("3")) {
Value = "other";
}
}
Invoicemain.put (key, value);
}
}
iterator<object> ITR = Invoicemain.keyset (). Iterator ();
while (Itr.hasnext ()) {
Object key = Itr.next ();
Object value = Invoicemain.get (key);
System.out.println ("key:" + key + "; Value:" + value);
}
return invoicemain;
}
}
Java operations on MySQL database