Reprint please specify the original address: http://www.cnblogs.com/ygj0930/p/5847020.html
Learning Java development, a must grasp the knowledge point, is the database operation. When a program needs to reach a certain level of data, it cannot simply be stored in a local file, but with a database.
At present, the most used database has mysql,oracle, and so on, Java programming in the connection, the use of different database operations are very similar, here the MySQL database for example.
JDBC programming is not difficult, there is a fixed use of routines:
1) Load Driver driver: Class.forName ("Com.mysql.jdbc.Driver");
2) Create a database connection object and log in to the database: Connection conn=drivermanager.getconnection ("jdbc:mysql://... (address, port), "Database user name", "Database Password");
3) Create a Routing object that can send SQL commands to the database and return the results: Statement statement=conn.createstatement ();
4) Create the SQL command and execute: String sql= "SQL command statement"; Statement.executeupdate (SQL); resultset=statement.executequery (SQL);
5) If the query class command is executed, a result set is returned, and the result set is processed to obtain specific data for the specific properties of each record:
while (Resultset.next ()) {int/double/string a=resultset.getint/double/string ("property name");}
Note: The result set is a table, the first row is the property name, the second row is the specific data, so first move the cursor through Resultset.next () to the second row, see if there is data, and then extract.
6) Close result set: Resultset.close ();
7) Close the corresponding Statement object: Statement.close ();
8) Close the Connection object Connection:conn.close ();
Apply to code instance:
public string Dologin (String Code_input,int password_input)
{
Connection Conn=null;
Statement Stmt=null;
ResultSet Rs=null;
try{
Class.forName ("Com.mysql.jdbc.Driver");
Conn=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/bank", "root", "123456");
Stmt=conn.createstatement ();
String sql= "SELECT * from account where code = '" +code_input+ "' and password =" +password_input;
Rs=stmt.executequery (SQL);
if (Rs.next ())
{
return code_input;
}else{
Return "-1";
}
}catch (Exception ex)
{
Ex.printstacktrace ();
Return "-1";
}finally
{
if (rs!=null)
{
try{
Rs.close ();
}catch (Exception ex)
{
Ex.printstacktrace ();
}
}
if (stmt!=null)
{
try{
Stmt.close ();
}catch (Exception ex)
{
Ex.printstacktrace ();
}
}
if (conn!=null)
{
try{
Conn.close ();
}catch (Exception ex)
{
Ex.printstacktrace ();
}
}
}
}
"Java" JDBC programming routines