JDBC-java connection database

JDBC is an interface for java to connect to the database. When we use it, we can call it directly. The following are the steps to connect to the database in java, because I have just started learning, if there is something wrong, please give me some pointers.

Here we take the mysql database as an example. In fact, the method is the same, just change the name when calling.

step:

1. Register the driver;

2. Create a connection;

3. Get the database object;

4. Execute the sql statement;

5. Processing statements;

6. Release resources;

Here is the code for your reference:

//需要的包
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.cj.jdbc.Driver;

public class JDBC02 {
	public static void main(String[] args) {
		Connection con=null;
		Statement sta=null;
		ResultSet rs=null;
		try {
			//1.注册驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("数据库连接成功!");
			//2.创建连接
	con=DriverManager.getConnection("jdbc:mysql://localhost/demo","root","123456");
			//3.获得数据库对象
			sta=con.createStatement();
			//4.执行sql语句
			//statement 执行sql语句时,属性值可以用"++"来设置
			String sql="select * from user where username='"+111+"'and password='"+ 123456+"'";
			rs=sta.executeQuery(sql);//executeQuery用于处理结果集
			//sta.executeUpdate(sql)用于insert、delete、update
			//5.处理语句
			if(rs.next()){
             //获得数据可以用get方法,常用的则为rs.getString(a)这里a为数据库表格中的列,默认第一列为1
				String id=rs.getString(1);
				String username=rs.getString(2);
				String password=rs.getString(3);
				String email=rs.getString(4);
				System.out.println(id+" "+username+" "+password+" "+email);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
		finally {
			//6.释放资源  从小往大释放,例如先释放结果集rs,在释放数据库对象sta,最后释放驱动con
			if(rs!=null){
				try {
					rs.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				if(sta!=null){
					try {
						sta.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
					if(con!=null){
						try {
							con.close();
						} catch (Exception e2) {
							// TODO: handle exception
						}
					}
				}


			}

		}
	}
}

Guess you like

Origin blog.csdn.net/qq_52705208/article/details/124770970