Java string / stringbuilder在mysql数据库

时间:2016-01-30 12:20:37

标签: java mysql string stringbuilder

Java String始终向mysql数据库发送null。  这将以等宽字体显示。前四个空格     将被剥离,但所有其他空白将被保留。

Markdown and HTML are turned off in code blocks:
<i>This is not italic</i>, and [this is not a link](http://example.com)

我有一个程序在命令提示符下工作正常并提供所需的输出但是当我将值保存到数据库时它始终保存为null。

void hddName(String ip) {

  try {
         String commands="cmd /c wmic.exe DISKDRIVE  get name";//HDD Details
         //System.out.println({"CMD", "/C", "WMIC OS GET Installdate,SerialNumber"});
         Process process = Runtime.getRuntime().exec(commands);
         process.getOutputStream().close(); //Closing output stream of the process
         System.out.println();
         StringBuilder sb=new StringBuilder();
        //Reading sucessful output of the command
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while ((s = reader.readLine()) != null)
    {
        sb.append(s).toString();//append output 
    }
        System.out.println("result"+sb);//gives result with null keyword
        String ss=sb.toString();//gives result with null keyword
        System.out.println("result"+ss);
        try{
                System.out.println(s);
                Connection conn;
                Statement stmt;
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/system","root","");
                stmt= conn.createStatement();
                String sql="update sys set hdname='"+ss+"' where ip='"+ip+"'";// save null to mysql database
                int val= stmt.executeUpdate(sql);  
                conn.close();
                stmt.close();
            }
            catch(Exception e)
            {

            }
    // Reading error if any
    reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    while ((s = reader.readLine()) != null)
    {
     System.out.println(s);//any error
    }
   } 
  catch (IOException e)
 {
   e.printStackTrace(); //TODO: necessary exception handling
  }
  // return s;
 }

3 个答案:

答案 0 :(得分:0)

在sysouts中打印为null吗? sb allways null?

    System.out.println("result"+sb);//gives result with null keyword
    String ss=sb.toString();//gives result with null keyword
    System.out.println("result"+ss);

尝试

String ss= "";
    //Reading sucessful output of the command
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getOutputStream()));
while ((s = reader.readLine()) != null)
{
    ss = ss + s.toString();//append output 
}

希望它有所帮助。

答案 1 :(得分:0)

永远不要将值作为SQL的一部分嵌入。您使程序容易受到SQL注入的攻击。<​​/ p>

做类似的事情:

stmt= conn.prepareStatement("update sys set hdname= ? where ip=?");
stmt.setString(1, ss);
stmt.setString(2, ip);
stmt.executeUpdate();

如果您确定ss不是null,则问题可能是由您的方法构造的奇怪SQL引起的。

答案 2 :(得分:0)

这是因为BufferedReader。因为我是从缓冲区读取的。最后它将null放在变量中。所以,我首先将输出写入文件,然后从中读取,然后保存到数据库。