对MySQL数据库数据操作之修改

对数据库的修改操作:

代码:

<pre name="code" class="java">package cn.edu.hpu.operate;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class Update {
	private static  String driver = "com.mysql.jdbc.Driver";
	private static  String url =  "jdbc:mysql://localhost:3306/数据库名";
	
	public static Connection getConn()
	{
		Connection conn = null;
		try
		{
			Class.forName(driver);
		}
		catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		try
		{
			conn = (Connection) DriverManager.getConnection(url,"用户名","密码
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		return conn;
	}
	public static void main(String[] args)
	{
		//修改
		int i = 0;
		String sql="update student set s_id=?,s_name=?,s_sex=?,s_age=? where (s_id=103)";

		Connection cnn = getConn();
		
		try
		{

			PreparedStatement preStmt = cnn.prepareStatement(sql);//修改数据,注意修改数据类型,注意set方法,括号中第一个数字是指针,第二个是修改后的数据
			preStmt.setInt(1, 103);
			preStmt.setString(2,"孙俪");
			preStmt.setString(3,"女");
			preStmt.setInt(4, 24);
			i =i+ preStmt.executeUpdate();
			
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		System.out.println(i);//输出i的值为1表示数据修改成功
	}

}


 

你可能感兴趣的:(对MySQL数据库数据操作之修改)