Jump to content

Inserir dados na base de dados


Recommended Posts

Posted (edited)

Boas, tenho este código no form categorias para inserir e dá-me erro "Object reference not set to an instance of an object." o get_id tem o return id na classe

con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DataBase.mdf;Integrated Security=True;User Instance=True";

con.Open();

try

{

SqlCommand command = con.CreateCommand();

if (val == "editar")

command.CommandText = "UPDATE Categorias SET Categorias='" + nomeTextBox.Text + "' where ID='" + m.get_id() + "'";

else

command.CommandText = "INSERT INTO Categorias VALUES (" + m.get_id() + ",'" + nomeTextBox.Text + "')";

command.CommandType = CommandType.Text;

SqlDataReader reader = command.ExecuteReader();

reader.Close();

}

catch (Exception er)

{

MessageBox.Show(er.ToString());

}

con.Close();

MessageBox.Show("Guardado");

no formeditarcat no botao criar tenho este código

con = new System.Data.SqlClient.SqlConnection();

con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DataBase.mdf;Integrated Security=True;User Instance=True";

con.Open();

SqlCommand command1 = con.CreateCommand();

command1.CommandText = "SELECT MAX(ID) FROM Categorias";

int num = (Int32)command1.ExecuteScalar();

num++;

con.Close();

Categorias m = new Categorias(num, "Nova Categoria");

CategoriasForm x = new CategoriasForm(m);

x.ShowDialog();

Edited by gregurs
Posted

Tem como mostrar em qual linha este erro acontece? Este erro ocorre quando se tenta acessar um objeto nulo, é mais fácil corrigir o erro se soubermos onde o erro apareceu.

Fernando Lage Bastos - MCP/MCTS/MCPD

Posted

aparece nesta linha

command.CommandText = "INSERT INTO Categorias VALUES (" + m.get_id() + ",'" + nomeTextBox.Text + "')";

Posted (edited)

este m é o que? Se for um objeto, ele foi instanciado?

Edited by petvetbr

Fernando Lage Bastos - MCP/MCTS/MCPD

Posted (edited)

consegui inserir um registo o problema era que tinha c=m e não m=c

public CategoriasForm(Categorias c)

{

InitializeComponent();

m = c;

}

Mas parece com id 0 e quando tento inserir outro registo dá erro

"Violation of PRIMARY KEY constraint 'PK__Categori__3213E83F61316BF4'. Cannot insert duplicate key in object 'dbo.Categorias'. The duplicate key value is (0).

The statement has been terminated."

Edited by gregurs
Posted

Isto ocorre porque já existe um registro com id de 0. Só pode haver um elemento com cada id, assim ocorre um erro ao tentar gravar outro com id=0.

Fernando Lage Bastos - MCP/MCTS/MCPD

Posted

se o banco de dado já está com AutoIncrement ligado, você não precisa passar o ID durante o insert, somente as outras colunas. Se o banco de dados não recebe o id e ele com autoincrement ligado, ele se encarrega de colocar um valor válido. Se não estiver ligado, procure na documentação ou internet como ativar isto no banco de dados que estiver utilizando.

Fernando Lage Bastos - MCP/MCTS/MCPD

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.