我试图用Visual Studio创建一个localdb。我使用c#连接和插入新行。我不了解问题是在Visual Studio服务器资源管理器数据库连接中还是在我的代码中。
要将行插入数据库,我从[Using SqlDataAdapter to insert a row 。当用户单击按钮时,此连接应正常工作,但调试时出现空引用异常
import java.time.LocalDate;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Conteudo {
private final ObjectProperty<LocalDate> data = new SimpleObjectProperty<>(this, "data",null);
private final StringProperty aula = new SimpleStringProperty(this, "aula",null);
private final StringProperty conteudo = new SimpleStringProperty(this, "conteudo", null);
public Conteudo() {
this(null, null, null); // chama outro construtor
}
public Conteudo(LocalDate dt, String au, String cont) {
this.data.set(dt);
this.aula.set(au);
this.conteudo.set(cont);
}
public void setDate(LocalDate dt) {
data.set(dt);
}
public LocalDate getDate() {
return data.get();
}
public final ObjectProperty<LocalDate> dateProperty() {
return data;
}
public void setAula(String au) {
this.aula.set(au);
}
public String getAula() {
return aula.get();
}
public void setConteudo(String cont) {
this.conteudo.set(cont);
}
public String getConteudo() {
return conteudo.get();
}
}
我在Visual Studio中创建了3个localdb,所以只有其中一个已连接。也许我使用的是错误的。如果变量con中有问题,我该怎么理解? 为了轻松实现问题,调试时的con值在下面;
SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename= C:\somepath.mdf; Integrated Security = True;");
con.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT * FROM mytablename WHERE 0 = 1", con);
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet);
DataRow newRow = dataSet.Tables["mytablename"].NewRow(); // null reference exception
newRow["username"] = "un";
newRow["myaccountusername"] = "maun";
dataSet.Tables["mytablename"].Rows.Add(newRow);
new SqlCommandBuilder(sqlDataAdapter);
sqlDataAdapter.Update(dataSet);